Finding the last exception object in your custom ASP.NET MVC error handler page

Posted: (EET/GMT+2)

 

Received today a question from the field related to ASP.NET MVC application exception handling and the custom error page Error.cshtml in the Views/Shared folder.

By default, ASP.NET MVC applications (version 3 onwards) specify the HandleError attribute as a global attribute, and thus by default all exceptions happening in action methods of controllers are handled by the Error.cshtml (or Error.vbhtml) file.

However, it's not immediately clear how you would access the last exception object from this view. If you have previous ASP.NET WebForms experience, you might be looking into the Server.GetLastError method, but this does not return the latest exception in this case.

Instead, you have to look at the very beginning of the Error.cshtml file for a clue:

@model System.Web.Mvc.HandleErrorInfo

This means that by default, the Error.cshtml view page receives a Model object that you can access. It contains the last exception object in the property named Exception, and also contains the name of the offending controller and action method.

In essence, this is the declaration of the HandleErrorInfo class:

public class HandleErrorInfo
{
    public string ActionName { get; }
    public string ControllerName { get; }
    public Exception Exception { get; }
}

Thus, the solution turns out to be pretty simple! In your Error.cshtml, you could show the exception text like this:

@Model.Exception

Remember, you just have to think in "the MVC way" instead of the "WebForms way".

Hope this helps!

Keywords: How to get last exception raised/thrown in ASP.NET MVC custom error page