5

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.

2
  • You want to see it whilst you're debugging? Commented May 11, 2012 at 20:06
  • not while debugging. i want the Trouble action to inspect the thrown error and retrieve the error message to display to the end user Commented May 11, 2012 at 20:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's probably not as bad as you think, looking at previous questions it seems a way to go :)

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.