@[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());
}
}