Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Handling in asp.net mvc 3

Is there a built in or a proper way to handle errors in asp.net mvc 3?

This is what I want to do:

  1. If the application crashes, or throws an error, it goes to a specific error page.
  2. I can throw my own error from the controller action. (and it goes to an error page).

I found the following ways:

  1. I see there is a long way to do it here. (for v1 and v2 but also applies to v3).
  2. Using errorhandle attribute here.

How do I handle this the proper way?

If the solution is similar or is like #1 in the list above, I am using ninject and I have not created a base class. How do I still do this?

like image 713
Shawn Mclean Avatar asked May 13 '11 17:05

Shawn Mclean


People also ask

What is error handling in asp net core?

ASP.NET Core apps enable the developer exception page by default when running in the Development environment. The developer exception page runs early in the middleware pipeline, so that it can catch unhandled exceptions thrown in middleware that follows.

What is exception handling in MVC C#?

Exception handling is the process of responding to the occurrence of exceptional conditions requiring special processing. Exception handling is important in any application. In ASP.NET we can handle exceptions in the following two ways: Try-catch-finally block at method level. Using Application_Error.


2 Answers

For Global Error Handling
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.

Make sure that Error.cshtml Layout is not null.
[It sould be something like: @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-

@{ Layout = "~/Views/Shared/_Layout.cshtml"; }   @model System.Web.Mvc.HandleErrorInfo  <!DOCTYPE html> <html> <head>     <title>Error</title> </head> <body>     <h2>         Sorry, an error occurred while processing your request.     </h2>     <p>Controller Name: @Model.ControllerName</p>     <p>Action Name : @Model.ActionName</p>     <p>Message: @Model.Exception.Message</p> </body> </html> 

For Specific Error Handling
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:

public class MyController: Controller     {         [HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]         public ActionResult Index()         {             throw new NotImplementedException("This method is not implemented.");             return View();         } } 
like image 100
Sunil Avatar answered Sep 22 '22 18:09

Sunil


I would suggest implementing a custom HandleErrorAttribute action filter.

See this link for more details:
http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx

Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.

Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.

UPDATE:

Per some questions below, here is an example of a HandleJsonErrorAttribute that I use:

public class HandleJsonErrorAttribute : HandleErrorAttribute {     public override void OnException(ExceptionContext filterContext)     {         var serviceException = filterContext.Exception as ServiceException;          filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;          filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };          filterContext.ExceptionHandled = true;     } } 

And here is the jQuery that I use to handle these unhanded exceptions:

$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {     showPopdown($.parseJSON(jqXHR.responseText).message); }); 

This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.

Also, in my implementation, I have a custom ServiceException that I throw from services, and this sends the message from the service layer instead of a generic message.

like image 23
Jerad Rose Avatar answered Sep 18 '22 18:09

Jerad Rose