You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.6 KiB
C#

using Estsh.Core.Model.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Estsh.Core.Util
{
/// <summary>
/// 全局异常处理中间件
/// </summary>
public class GlobalExceptionHandler
{
#region 属性及其构造函数
private readonly RequestDelegate _next; //上下文请求
private readonly ILogger<GlobalExceptionHandler> _logger;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="next">上下文请求</param>
/// <param name="logger">日志对象</param>
public GlobalExceptionHandler(RequestDelegate next, ILogger<GlobalExceptionHandler> logger)
{
_next = next;
_logger = logger;
}
#endregion
#region 处理上下文请求
/// <summary>
/// 处理上下文请求
/// </summary>
/// <param name="httpContext">http会话对象</param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
//_logger.LogInformation(httpContext.Request.Path);
await _next(httpContext); //处理上下文请求
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex); //捕获异常,在HandleExceptionAsync中处理
}
}
#endregion
#region 全局统一异常处理
/// <summary>
/// 全局统一异常处理
/// </summary>
/// <param name="context">http会话对象</param>
/// <param name="exception">全局异常处理</param>
/// <returns></returns>
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json"; //返回json 类型
var response = context.Response;
var errorResult = new ErrorResult { Success = false };
// 自定义的异常错误信息类型
switch (exception)
{
case ApplicationException ex:
response.StatusCode = (int)HttpStatusCode.BadRequest;
errorResult.Message = ex.Message;
break;
case Exception ex:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
errorResult.Message = ex.Message;
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
errorResult.Message = "Internal Server Error";
break;
}
//错误日志控制台输出
_logger.LogError(exception.Message);
//错误日志文件输出
var errorInfo = new StringBuilder();
errorInfo.AppendLine("Time:" + DateTime.Now);
errorInfo.AppendLine("StackTrace:" + (exception.StackTrace == null ? "" : exception.StackTrace));
errorInfo.AppendLine("Source:" + (exception.Source == null ? "" : exception.Source));
errorInfo.AppendLine("Message:" + exception.Message);
errorInfo.AppendLine("InnerExceptionMessage:" + (exception.InnerException == null ? "" : exception.InnerException.Message));
LogHelper.Error(errorInfo.ToString());
//返回统一异常
await context.Response.WriteAsync(errorResult.ToJson());
}
#endregion
}
}