Controller exception handling in ASP.Net MVC 4 with ELMAH and ajax

I saw several posts and articles, but could not clearly consider the solution.

I installed Elmah.MVC via NuGet and commented out this line from FilterConfig.cs:

//filters.Add(new HandleErrorAttribute()); 

So Elma will pick up the mistakes.

It works when I provide an invalid action name, and receive a yellow page as well as an email.

I want to know about two other types of errors that my code can generate ... how we should handle them:

1.Eg if my repository or manager resource (business logic) throws an exception when trying to access the database or send email, etc.

a. Is the right way to NOT implement any attempts at controllers (or anywhere else for that matter) and let Elmah take care of exceptions?

b. If so, and if it shows a page with a yellow error, how can we show our own preference?

2.If my view contains ajax calls, for example. through jqgrid, and errors appear behind the scenes, I noticed that they are also correctly matched by Elma. But how can I show some kind of error message to the user?

thanks

+4
source share
3 answers

Here is what I did:

In the controller, I set try catch:

  try { //model = getmodelfromdb(); return View("MyView", model); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return View("../Error/ShowException", ex); } 

For custom view for 404, I did this in global.asax:

  protected void Application_OnError( ) { var exception = Server.GetLastError( ); Elmah.ErrorSignal.FromCurrentContext().Raise(exception); Helper.SetSessionValue(SessionKeys.EXCEPTION, exception); Response.Redirect( "~/Error/ShowException"); } 

For jqgrid, I did this in my controller:

  [HttpPost] public ActionResult ListRecords( int page , DateTime? fromdate , DateTime? todate) { try { var list = FetchListFromDB(); var result = new { total = Math.Ceiling(list.Count / (decimal)Helper.PAGE_SIZE), page = page, //--- current page records = list.Count, //--- total items rows = list.List.Select(x => new { id = x.EntityID, cell = new string[] { x.Property1, x.Property2 } }).ToArray() }; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { var result = new { errorMessage = "An unexpected error occurred while fetching data. An automatic email has been generated for the support team who will address this issue shortly. Details: " + ex.Message, records = 0 }; Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return Json(result, JsonRequestBehavior.AllowGet); } 

And this is in the view (in the jqgrid definition):

  loadComplete:function(data) { if (data.errorMessage) { alert(data.errorMessage); } }, 

In ajax common scenario:

  success: function(data) { if (data.errorMessage) { alert(data.errorMessage); } else { //... } }, 
+4
source

a. Is the right way to NOT implement any capture attempts in controllers (or anywhere else in this case) and let Elmah take care of exceptions?

I would say that Elma does not "care" about exceptions; he writes them down. Ideally, you should try to handle the errors - be sure to register them, but also add logic to deal with them so that they do not interrupt the user's workflow.

I would wrap the logic in try blocks, and in catch I would use

 Elmah.ErrorSignal.FromCurrentContext().Raise(exception); 

write down everything that goes wrong. However, immediately after this line, I would try to correct the situation from the exception - to catch specific types of exceptions, not just catch (Exception e) , and to deal with them after registering them. The idea is that you have to review your journals, develop what throws exceptions, and improve your program so that it no longer throws exceptions.

To show your own error pages, there is a HandleErrorAttribute , or if you do not want to use it, there is also an OnException() controller, which is called when the controller action method finishes with an exception and does not end normally. The ExceptionContext object is passed to this method, so you can use it to get the exception that was thrown and register it, perform any cleanup that might be required, etc.

+2
source

I know I'm very late to the party, but I came across this answer when I was looking for something like this on Google.

I don't like to use try catch blocks everywhere in my code, especially in web applications. I let Elma catch everything and put it in a magazine backstage. Then in the web.config file you can redirect based on the type of error ...

  <customErrors mode="RemoteOnly" defaultRedirect="~/Error" > <error statusCode="500" redirect="~/Error"/> <error statusCode="404" redirect="~/NotFound"/> </customErrors> 
0
source

Source: https://habr.com/ru/post/1496604/


All Articles