1

I have a c# controller and inside a method I have code with a try catch statement:

My controller has a top level class attribute LogAttribute:

public class LogAttribute : HandleErrorAttribute
{
    public ILogManager Logger { get; set; }

    public override void OnException(ExceptionContext filterContext)
    {
        Exception exception = filterContext.Exception;
        filterContext.ExceptionHandled = true;

        /* start log error */
        var logHelper = new Helpers.LogHelper (this.Logger);
        Guid errorUid = Guid.NewGuid();

        // call log4net
        logHelper.LogErrorString(errorUid, exception);
        /* end log error */
     }

}

[Log]
public class TestController 
{
   public JsonResult TestMethod(){

       try{

           //...some code here

           List<string> list = null;

           //Line 65 force expection Object reference not set to an instance of an object
           list.count(); 

       } 
       catch(Exception ex) {


           // ... do some code here

           throw ex; // Line 82
       }

      return null;
   }
}

The Log4Net logging is working fine but when I debug just after the catch and see the Exception ex I can see that the StackTrace line is the 65 as the exception line, and this is totally correct because is where the exception happened. But when Log4Net logs the error it shows as lines 82 that is exactly where I manually trhow the exception.

** UPDATE **

I just checked that the excepction StackTrace is correct in the Catch statement but exactly when the MVC Log attribute OnException handler catch that then the stacktrace is being reset. So is problem of the OnException method.

Any clue?

VAAA
  • 14,531
  • 28
  • 130
  • 253
  • 3
    read on `throw;` vs. `throw ex;` (probably can close as duplicate of https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex) – Alexei Levenkov Sep 19 '19 at 01:59
  • Just change that and issue still the same – VAAA Sep 19 '19 at 02:12
  • I don't thing issue remains if you have `throw;` inside your `catch` block. Make sure you recompiled and restarted your application. – fenixil Sep 19 '19 at 03:27
  • Make sure your other try catch blocks use throw as well. This inner try catch block is likely being overriden. – JReno Sep 19 '19 at 04:56
  • What I ended to is to throw a new exception passing as inner exception the actual one. And that solves the problem. – VAAA Sep 19 '19 at 14:19

0 Answers0