在MVC应用程序中,我们如何使用Microsoft异常处理应用程序块显示标准MVC错误页面以及处理异常?
我已经更新了我的web.config文件
在异常时重定向到Trouble视图。但异常处理应用程序块(下面的代码)不再处理该异常。 ExceptionPolicy.HandleException(例如,“AllExceptions”,out errorToThrow);
如何显示错误视图以及处理异常?我不想使用ELMAH。
答案 0 :(得分:1)
使用Log4net和HttpHandler进行日志记录和错误处理。请参阅以下示例代码。并使用相同的ExceptionHandler
属性装饰控制器。(
[ExceptionHandler]
public class BillsController : Controller
{ }
)
public class ExceptionHandler : HandleErrorAttribute
{
private static readonly ILog log = LogManager.GetLogger(typeof(ExceptionHandler));
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
log.Debug("******** ExceptionHandler.OnException() *****************");
base.OnException(filterContext);
Exception ex = filterContext.Exception;
if (filterContext.Exception is BusinessException)
{
log.Debug("<<<<Inside On BusinessException....>>>>" + DateTime.Now);
//log.Debug("*** Error Getting From **** " + LOGIN_DETAILS.LoginUserName +
// "(UserId = " + LOGIN_DETAILS.LoginUserID + ")" + "Time =" + DateTime.Now);
BusinessException _BusinessException =
(BusinessException)filterContext.Exception;
StringBuilder errormsg = new StringBuilder();
foreach(MessageInfo msg in _BusinessException.ErrorMessageList)
{
errormsg.AppendLine(msg.LocalizedMessage);
}
log.Error("<<<<--------BusinessException-------->>>> : Exception Details -----"+ errormsg.ToString());
//filterContext.ExceptionHandled = true;
filterContext.ExceptionHandled = true;
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Account", action = "Logout", message = filterContext.Exception.Message })).VirtualPath;
filterContext.HttpContext.Response.Redirect(url, true);
}
else
{
log.Error("Exception Details ---- " +
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\\Controller: " + filterContext.Controller.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
ex);
filterContext.ExceptionHandled = true;
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Exception", action = "Default" })).VirtualPath;
//string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "exception", action = "Default", message = filterContext.Exception.Message })).VirtualPath;
filterContext.HttpContext.Response.Redirect(url, true);
}
}
}
答案 1 :(得分:1)
更改您的web.config文件以显示自定义错误,这样您就可以显示错误页面。
然后为了处理异常,将此函数添加到global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
//handle the exception
}