Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle errors with ErrorController rather than a direct view

I'm trying to get my head around the Error Handling in MVC. What I'm looking for is a centralized way to catch errors, log them, if possible resolve them, if nessecary take other actions and finally show the correct view to the user.

I think I can use the [HandleError] filter for this, but I don't see any way to route it to a Controller/Action. The only option I see is pointing it directly to a view.

like image 772
Boris Callens Avatar asked Oct 13 '08 12:10

Boris Callens


People also ask

What is used to handle an error in MVC?

ASP.NET MVC has HandleError Attribute (Action Filter), which provides one of the simplest ways to handle errors. HandleError Attribute has a couple of properties which are useful in handling an exception and help in modifying the default behavior of HandleError Attribute.

How do you handle errors in razor view?

How to handle errors in Razor Syntax? As you know razor allows you to full implementation of c# or vb so you can use exception handling inside razor syntax with try, catch, finally block.

Which of the following code shows how exceptions are handled in MVC?

HandleError Attribute This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.


1 Answers

HandleErrorAttribute that comes with MVC is a pretty basic IExceptionFilter.

You have a few options to achieve what i think u want.

You can either use [HandleError (Type=typeof(MyException),View="ErrorView")] on actions/controllers or implement your own

HandleErrorAttribute isnt very complex. I think MS recommends you copy this code and modify to suit your requirements.

The OnException override gives you access to all that info you may need - controller, action, route data, etc - through ExceptionContext.

Remember to set the ExceptionHandled. Then you can set the filterContext.Result to a new RedirectToAction instance which redirect to your ErrorController and action - obviously you can expose the specific controller and action with properties.

like image 199
CVertex Avatar answered Oct 19 '22 23:10

CVertex