4

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;
}

1 Answer 1

9

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.