---
# System prepended metadata

title: mod05
tags: [mvc]

---

```csharp
// homecontroller.cs
public ActionResult ExceptionDemo()
{
    int i = 0;
    int j = 10 / i;
    return View();
}

// home/index.cshtml
@Html.ActionLink("ExceptionDemo", "ExceptionDemo") |
    
//web.config
<system.web>
  <customErrors mode="On"></customErrors>
//==============================
// HomeController.cs
protected override void OnException(ExceptionContext filterContext)
{
    //base.OnException(filterContext);
    filterContext.ExceptionHandled = true;
    ViewData["Message"] = filterContext.Exception.Message;
    filterContext.Result = View(nameof(Index));
}
// Home/Index.cshtml
<h1>Home - @ViewData["Message"]</h1>       

@Html.ActionLink("ExceptionDemo", "ExceptionDemo") |
//==================================
// shared/error.cshtml
<div> 
    <h1>網站發生異常...</h1>
</div>

// global.asax.cs
protected void Application_Start()
{   

    GlobalFilters.Filters.Add(new HandleErrorAttribute());
//====================================
// shared/error2.cshtml
@model HandleErrorInfo
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error</title>
</head>
<body>
    <div> 
        <h1 style="color:red;">網站發生異常...</h1>
        <ul>
            <li>Status Code: @Context.Response.StatusCode</li>
            <li>Message: @Model.Exception.Message</li>
        </ul>
    </div>
</body>
</html>
                
//global.asax.cs
//GlobalFilters.Filters.Add(new HandleErrorAttribute());
GlobalFilters.Filters.Add(new HandleErrorAttribute {View="Error2" });
//========================
//web.config
<system.web>
  <customErrors mode="On">
	  <error statusCode="404" redirect="~/404.html"/>
  </customErrors>
//====================
//web.config
<system.webServer>
    <httpErrors errorMode="Custom">
      <remove statusCode="404"/>
      <error statusCode="404" path="/404.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>
```