Search code examples
asp.netexceptionowinasp.net-core-mvcmiddleware

MVC6 - Handle unhandled exceptions and still have error page redirection


In my MVC6 application, I have created a middleware to handle global unhandled exceptions with Invoke task as below:

try
{
    await _next.Invoke(context);
}
catch (System.Exception e)
{
    ... Log the exception here...
}

The issue i am facing is, if i add this in the configure section before adding UseDeveloperExceptionPage/UseExceptionHandle, then catch block in middleware is not being hit. When i add this after UseDeveloperExceptionPage/UseExceptionHandle, the error page or module are not getting processed.

How can i not disturb the error page/module but still catch the error in the pipeline and log it?

Thanks in advance.


Solution

  • This is because the Exception page needs to have an Exception object to work with. Your code catches the exception which is then suppressed. Try rethrowing the exception like so:

    try
    {
        await _next.Invoke(context);
    }
    catch (System.Exception e)
    {
        //Log the exception here...
        throw;
    }