1.首先捕获错误信息
/*[HandleError]:此属性指定此类出错时捕获错误信息;
* 此属性其实可以不指定,因为Global.asax.cs默认所有的控制器出错都会捕获错误信息,* 见filters.Add(new HandleErrorAttribute()),这两种方法有一即可;
*/
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
int[] a = { 1,2,3};
int b = a[4]; //故意的错误,溢出
return View();
}
public ActionResult About()
{
return View();
}
}
2.配置中开启错误重定向页
<customErrors mode="On"defaultRedirect="~/Error/HttpAllError">//默认都重定向到此页
<error statusCode="404"redirect="~/Error/NoFound"/> //404错误重定向到此页
</customErrors>
3.创建错误页控制器和视图
控制器代码:
public class ErrorController :
Controller
{
//
// GET: /Error/
public ActionResult HttpAllError()
{
return View("Error");
}
public ActionResult NoFound()
{
return View();
}
}
View页面代码,这些异常信息好好利用:
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
<h2>
A General Error Has Occurred</h2>
@if (Model != null)
{ <p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p> <p>
Error Details:</p> <p>@Model.Exception.Message</p>
}