Tom*_*eck 5 error-handling asp.net-mvc-3
我在webconfig中打开了自定义错误并重定向到"/ Error/Trouble".这是按设计工作的.Elmah正在记录错误.错误视图也在显示.
问题是我想检查我的Error控制器的Trouble操作中的抛出错误.当抛出错误时,在MVC将您重定向到自定义错误处理程序后,如何访问它?
如果CurrentUser为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"));
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在我的自定义错误处理程序("错误/故障")中访问它.你如何访问例外?
这是我的麻烦行动:
public ActionResult Trouble()
{
return View("Error");
}
Run Code Online (Sandbox Code Playgroud)
这是我的观点:
@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>
}
Run Code Online (Sandbox Code Playgroud)
System.Web.Mvc.HandleErrorInfo是我的Trouble视图的模型,它是空的.谢谢你的帮助.
我找到了一个解决方法:
在 Global.asax 中我这样做:
protected void Application_Error()
{
var exception = Server.GetLastError();
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["TheException"] = exception;
HttpContext.Current.Application.UnLock();
}
Run Code Online (Sandbox Code Playgroud)
在错误/麻烦中我这样做:
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);
Run Code Online (Sandbox Code Playgroud)
这是有效的。但这似乎是一种奇怪的处理方式。有人有更好的解决方案吗?感谢您的帮助。