raj*_*lai 3 asp.net asp.net-mvc exception-handling
我想了解一些处理ASP.NET MVC中未处理异常的策略/实践.
总之,我想在发生任何错误时避开黄色屏幕,并向访问者显示错误一致的错误消息.
我的意思是你为此编写了一个控制器,它显示了相应的错误页面,或者你采取其他方式编写一个httpmodule并在全局级别捕获错误.
这方面的任何投入都表示赞赏.
使用HandleError属性是要走的路.这是一个小样本,我用它来处理来自JQuery,ExtJs等的Ajax调用.
在你的控制器上
public class DataController : Controller
{
[HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorAjax")]
public void Foo(string x, string y)
{
if (String.IsNullorEmpty(x))
throw new ArgumentException("String cannot be empty!");
// Call your layers or whatever here
AnotherCall();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的视图(ErrorAjax).注意它是强类型的(HandleErrorInfo)
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sorry Dude!</title>
</head>
<body>
<div>
<!-- be creative here-->
Sorry, an error occurred while processing your request.
Action = <%= ViewData.Model.ActionName %>
Controller = <%= ViewData.Model.ControllerName %>
Message = <%= ViewData.Model.Exception.Message %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
几个陷阱