Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error status code in ASP.NET MVC

I am using ASP.NET MVC and the below code to return an exception description and store it in a session. I need help finding out the error code of the exception, like 500, 403, 404, etc. How can I do that?

This is how I am storing the error message in a session:

System.Web.HttpContext.Current.Session["errorMessage"] = filterContext.Exception.Message.ToString();

public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
    ProcessResult processResult = new ProcessResult();

    // If the exception is already handled, we do nothing
    if (filterContext.ExceptionHandled)
    {
        return;
    }
    else
    {
        var controllerName = (string)filterContext.RouteData.Values["controller"];
        var actionName = (string)filterContext.RouteData.Values["action"];
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
        processResult.Controller = controllerName;
        processResult.Action = actionName;
        processResult.ExceptionMessage = filterContext.Exception.Message;
        System.Web.HttpContext.Current.Session["errorMessage"] = filterContext.Exception.Message.ToString();
        processResult.StackTrace = filterContext.Exception.StackTrace;
        processResult.Source = filterContext.Exception.Source;
    }
    // Mark the exception as handled
    filterContext.ExceptionHandled = true;
}
like image 737
Kurkula Avatar asked Jan 11 '23 20:01

Kurkula


1 Answers

Check to see if the Exception is an HttpException. Then cast it as such and grab the status code.

if (filterContext.Exception is HttpException)
{
    var statusCode = ((HttpException)filterContext.Exception).GetHttpCode();
}
like image 196
Rowan Freeman Avatar answered Jan 17 '23 21:01

Rowan Freeman