C# 全局异常

@[TOC]C# 全局异常
1.WebApiConfig
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new GlobalExceptionFilter());
}
Global.asax.cs
2.Application_Error
{
var lastError = Server.GetLastError();
if (lastError != null)
{
int statusCode;
string errorMsg = GlobalExceptionFilter.ErrorHandle(lastError, out statusCode);
Response.StatusCode = statusCode;
Response.Write(errorMsg);
Server.ClearError();
}
}
3.
public class GlobalExceptionFilter : IExceptionFilter
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public bool AllowMultiple => false;

    public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        if (actionExecutedContext.Exception != null)
        {
            OnException(actionExecutedContext);
        }
        return Task.CompletedTask;
    }

    public void OnException(HttpActionExecutedContext context)
    {
        Exception exception = context.Exception;
        HandleException(context, exception);
    }

    private void HandleException(HttpActionExecutedContext context, Exception exception)
    {
        LogException(exception);
        ShowErrorPage(context, exception);
    }
	  private void LogException(Exception exception)
    {
        logger.Error(exception.StackTrace);
    }

    public static void ShowErrorPage(HttpActionExecutedContext context, Exception lastError)
    {
        if (lastError != null)
        {
            int statusCode;
            string errorMsg = ErrorHandle(lastError, out statusCode);
            context.Response = new HttpResponseMessage((HttpStatusCode)statusCode)
            {
                Content = new StringContent(errorMsg, Encoding.UTF8, "text/html")
            };

        }
    }

    public static string ErrorHandle(Exception lastError, out int statusCode)
    {
        HttpException httpError = lastError as HttpException;
        if (httpError != null)
        {
            statusCode = httpError.GetHttpCode();
            return ShowHttpError(httpError);
        }
        else
        {
            statusCode = (int)HttpStatusCode.InternalServerError;
            return ShowInternalServerError(lastError);
        }
    }

    private static string ShowInternalServerError(Exception lastError)
    {
        return ShowErrorMessage(lastError, 500);
    }

    private static string ShowHttpError(HttpException httpError)
    {
        return ShowErrorMessage(httpError, httpError.GetHttpCode());
    }

    private static string ShowErrorMessage(Exception httpError, int httpCode)
    {
        string errorMsg = string.Empty;
        errorMsg += $"<h3>HTTP status code:</h3><label>{httpCode}</label>";
        errorMsg += $"<h3>Error message:</h3><label>{httpError.Message}</label>";
        if (hasStackTrace())
        {
            errorMsg += $"<h3>Stack trace:</h3><label>{httpError.StackTrace}</label>";
        }
        string responseContent = $"<!DOCTYPE html><html><head>    <meta charset=\"utf-8\" />    <title></title></head><body>  " +
        $" <h2>We're sorry, but an error has occurred while processing your request.</h2>" +
        $" {errorMsg}" +
        $"</body></html>";
        return responseContent;
    }

    private static bool hasStackTrace()
    {
        string env = Environment.GetEnvironmentVariable("ENV");
        return "prod".!=(env?.ToLower());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值