MVC3 アプリケーションでのエラー処理のために、カスタム エラー セクションで HandleErrorAttribute とカスタム エラー コントローラーを組み合わせて使用しています。ロジックは、HandleErrorAttribute の OnException ハンドラーを介してすべての Ajax 要求エラーを処理し、ErrorController を介して残りのエラーを処理することです。以下はコードです -
// Handle any ajax error via HandleErrorAttribute
public class HandleAjaxErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
var exception = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
//some logic
filterContext.ExceptionHandled = true;
}
}
}
//Handle remaining errors in the Error Controller
public class ErrorController : Controller
{
protected override void HandleUnknownAction(string actionName)
{
var exception = Server.GetLastError(); //Can't get the exception object here.
//some logic
}
}
Web.config 設定:
<customErrors mode="On" defaultRedirect="~/Error">
</customErrors>
ajax 以外の例外が発生すると、制御は OnException ブロックからエラー コントローラーの HandleUnknownAction に流れます。ただし、例外オブジェクトを取得できません。Error Controller で Exception オブジェクトを取得するにはどうすればよいですか?
また、この 2 段階のアプローチは MVC3 でエラーを処理する適切な方法だと思いますか? Application_Error イベント ハンドラーを使用して中央の場所でエラーを処理することを考えましたが、私の調査によると、これは MVC アプリケーションの推奨されるアプローチではありません。