在mvc的global.asax application_error 中处理全局错误。

如果在未到创建请求对象时报错,此时 context.handler == null

判断为ajax请求时,我们返回json对象字符串。不是ajax请求时,转到错误显示页面。

/// <summary>
/// 全局错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void application_error(object sender, eventargs e)
{
    exception ex = server.getlasterror();
    loghelper.error(ex); // 记录错误日志(nlog 挺好用的(* ̄︶ ̄))

    if (context.handler == null)
    {
        return;
    }

    if (new httprequestwrapper(request).isajaxrequest())
    {
        response.clear();
        response.contenttype = "application/json; charset=utf-8";
        response.write("{\"state\":\"0\",\"msg\":\"" + ex.message + "\"}");
        response.flush();
        response.end();
    }
    else
    {
        // 方案一 重定向到错误页面,带上简单的错误信息
        //string errurl = "/error/error?msg=" + ex.message;
        //response.redirect(errurl, true);

        // 方案二 带上错误对象,转到错误页
        response.clear();
        routedata routedata = new routedata();
        routedata.values.add("controller", "error"); // 已有的错误控制器
        routedata.values.add("action", "error"); // 自定义的错误页面

        server.clearerror();
        errorcontroller controller = new errorcontroller();
        handleerrorinfo handleerrorinfo = new handleerrorinfo(ex, "error", "error");
        controller.viewdata.model = handleerrorinfo;
        ((icontroller)controller).execute(new requestcontext(new httpcontextwrapper(((mvcapplication)sender).context), routedata));
    }
}

其中方案二的对象用法,与默认的错误页(即 /shared/error.cshtml)一样。当我们不对错误进行任何处理时,在web.config中可配置错误页到 /shared/error.cshtml。

error.cshtml的代码:

@model system.web.mvc.handleerrorinfo
@{
    viewbag.title = "系统错误";
    layout = "~/views/shared/_layout.cshtml";
}

<h3 class="text-danger">系统错误</h3>
@if (model != null)
{
    <span class="text-warning">@(model.exception.message)</span>
}
else
{
    <span class="text-warning">处理请求时出错。</span>
}

方案二的action的代码:

public actionresult error()
{
    return view();
}

相关配置影响:

<!--开启会导致异常不走application_error,直接寻error-->
<!--<customerrors mode="on" defaultredirect="~/error.cshtml" />-->