Error handling for ASP.NET MVC 2 and IIS 7.0

廉价感情. 提交于 2019-12-01 08:29:00

i use

protected void Application_Error(object sender, EventArgs e)

in my Global.asax.cs

to catch all unhanded exceptions, doing something like this inside it:

try
{
    Response.Clear();
    var errorController = new ErrorController();
    var result = errorController.Error(statusCode, exception);
    result.ExecuteResult(new ControllerContext(new RequestContext(new HttpContextWrapper(Context), routeData), errorController));
    Server.ClearError();
}
catch(Exception e)
{
    HttpContext.Current.Response.StatusCode = 500;
    HttpContext.Current.Response.Write(e.Message);
}

My Error controller looks like this:

public ActionResult Error(HttpStatusCode statusCode, Exception exception)
{
    var resource = new ErrorResource(statusCode, exception);
    this.response.StatusCode = resource.StatusCode;

#if !DEBUG
    return View("ReleaseError", resource);
#endif

    return View("DebugError", resource);            
}

I can then do:

throw new HttpException(404, "not found");

or

throw new HttpException(403, "not found);

etc programatically.

I think MVC2 introduced a new action result for error cases, not used it though, probably stinks like the rest of the framework.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!