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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With