Processing Error Using NLog and Try Catch

I log errors in my actions using NLog to store errors with additional information, for example:

using NLog; private static Logger _logger = LogManager.GetCurrentClassLogger(); public virtual ActionResult Edit(Client client) { try { // FORCE ERROR var x = 0; x /= x; return RedirectToAction(MVC.Client.Index()); } catch (Exception e) { _logger.Error("[Error in ClientController.Edit - id: " + client.Id + " - Error: " + e.Message + "]"); } } 

And I have error handling configured in Web.config:

 <customErrors mode="On" /> 

But I do not redirect to Error.cshtml when I execute an action (the page remains in the same place), why?

Can I use Elma to do the same? (recording additional information, such as customer ID)

+8
c # asp.net-mvc error-handling elmah nlog
source share
3 answers

First of all, most people solve this error without catching the exception. Thus, the exception applies to ASP.NET, which displays the "500 Internal Error" web page and all relevant information is logged.

  • If your server is set up for production, the error page will simply say: "an error has occurred, details have been registered."

  • If the server is configured for development, you will get the famous yellow page with the exception type, message and stack trace.

Swallowing the exception and manually redirecting to the error page is bad practice because it hides errors. There are tools that study your logs and give you good statistics, such as percentages of successful / unsuccessful requests, and they will no longer work.

So, not swallowing an exception is what people do, and at least it solves your problem.


Now I find this very awkward because I don’t like to manually search for the source files mentioned on the yellow page and manually jump to the specified line numbers. I practically do not use the yellow page, it can simply say: "An error has occurred, cry to me with the river, damn it." I do not read the yellow page.

Instead, I like to write exceptions myself, and I have a logger starting each line with full-path-to-source-filename(line): so that each line in the debug log in visual studio is clickable and clicking on the line automatically the right source file opens and scrolls to the exact line that issued the log message. If you want this luxury, then go ahead and catch the exception, but immediately after registering the exception, you must rebuild it so that everything can follow their normal course.

Amendment

Here is some info added in the comments:

So you can do the following:

 try { ... } catch (Exception e) { log( "information" ); throw; //special syntax which preserves original stack trace } 

or

 try { ... } catch (Exception e) { throw new Exception( "information", e ); //also preserves original stack trace } 

Do not do this: catch( Exception e ) { log( "information" ); throw e; } catch( Exception e ) { log( "information" ); throw e; } catch( Exception e ) { log( "information" ); throw e; } because it loses the original trace information of stack e .

+3
source share

An error occurs in your code in the division section (x / = x) , so the redirection line (index page) is not executed and the fragment executing the registrar is not executed. You must define a redirect to Error.cshtml in the catch section .

Note: when using the error, try catch block will not occur at the ASP.NET level, as a result of which it will not be redirected to the Error.cshtml page

 using NLog; private static Logger _logger = LogManager.GetCurrentClassLogger(); public virtual ActionResult Edit(Client client) { try { // FORCE ERROR var x = 0; x /= x; /// error occur here return RedirectToAction(MVC.Client.Index()); /// no execution of this line } catch (Exception e) { _logger.Error("[Error in ClientController.Edit - id: " + client.Id + " - Error: " + e.Message + "]"); /// add redirect link here return RedirectToAction(MVC.Client.Error()); /// this is needed since the catch block execute mean no error at ASP.net level resulting no redirect to default error page } } 
+1
source share

This will simplify the handling of exceptions and allow you to manage the process more succinctly. Create an attribute like this:

  public class HandleExceptionAttribute : System.Web.Mvc.HandleErrorAttribute { // Pass in necessary data, etc private string _data; public string Data { get { return _data; } set { _data = value; } } public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { // Logging code here // Do something with the passed-in properties (Data in this code) // Use the filterContext to retrieve all sorts of info about the request // Direct the user base.OnException(filterContext); } } 

Now you can use it at the controller or method level with this attribute:

 [HandleException(Data="SomeValue", View="Error")] 

Or register it globally (global.asax) as follows:

 GlobalFilters.Filters.Add(new HandleExceptionAttribute()); 
0
source share

All Articles