Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 3 get exception thrown

I have custom errors turned on in webconfig and redirecting to "/Error/Trouble". This is working as designed. Elmah is logging the error. The error view is being displayed too.

The problem is I want to inspect the thrown error in the Trouble action of my Error controller. When an error is thrown, how do you get access to it after MVC has redirected you to the custom error handler?

I'm throwing an exception if CurrentUser is null:

        if (CurrentUser == null)
        {
            var message = String.Format("{0} is not known.  Please contact your administrator.", context.HttpContext.User.Identity.Name);
            throw new Exception(message, new Exception("Inner Exception"));
        }

I want to be able to access this in my custom error handler ("Error/Trouble"). How do you access the exception?

Here's my trouble action:

    public ActionResult Trouble()
    {
        return View("Error");
    }

Here's my view:

@model System.Web.Mvc.HandleErrorInfo

<h2>
    Sorry, an error occurred while processing your request.
</h2>
@if (Model != null)
{
    <p>@Model.Exception.Message</p>
    <p>@Model.Exception.GetType().Name<br />
    thrown in @Model.ControllerName @Model.ActionName</p>
    <p>Error Details:</p>
    <p>@Model.Exception.Message</p>
}

System.Web.Mvc.HandleErrorInfo is the model for my Trouble view and it's empty. Thanks for your help.

like image 246
Tom Schreck Avatar asked Nov 04 '22 00:11

Tom Schreck


1 Answers

I found a workaround:

in Global.asax I do this:

        protected void Application_Error()
    {
        var exception = Server.GetLastError();

        HttpContext.Current.Application.Lock();
        HttpContext.Current.Application["TheException"] = exception;
        HttpContext.Current.Application.UnLock();
    }

In Error/Trouble I do this:

        var caughtException = (Exception)HttpContext.Application["TheException"];
        var message = (caughtException!= null) ? caughtException.Message : "Ooops, something unexpected happened.  Please contact your system administrator";
        var ex = new Exception(message);
        var errorInfo = new HandleErrorInfo(ex, "Application", "Trouble");
        return View("Error", errorInfo);

This is working. But it seems like a weird way to go about it. Does anyone have a better solution? Thanks for your help.

like image 182
Tom Schreck Avatar answered Nov 11 '22 16:11

Tom Schreck