74 lines
2.5 KiB
C#
74 lines
2.5 KiB
C#
using HuanMeng.DotNetCore.Base;
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
using System;
|
|
|
|
|
|
namespace HuanMeng.DotNetCore.MiddlewareExtend
|
|
{
|
|
/// <summary>
|
|
/// 异常中间件
|
|
/// </summary>
|
|
public class ExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<ExceptionMiddleware> _logger;
|
|
|
|
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
|
|
{
|
|
_next = next;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (ArgumentNullException ex)
|
|
{
|
|
|
|
|
|
context.Response.StatusCode = StatusCodes.Status200OK;
|
|
BaseResponse<object> baseResponse = new BaseResponse<object>(ResponseCode.Common, ex.ParamName ?? "参数错误", null)
|
|
{
|
|
|
|
};
|
|
context.Response.ContentType = "application/json; charset=utf-8";
|
|
// 将异常信息写入 HTTP 响应
|
|
await context.Response.WriteAsync(baseResponse.ToString());
|
|
}
|
|
catch (CustomException ex)
|
|
{
|
|
// 对自定义异常的特殊处理,不记录日志
|
|
context.Response.StatusCode = StatusCodes.Status200OK;
|
|
BaseResponse<object> baseResponse = new BaseResponse<object>(ResponseCode.Common, ex.ParamName ?? "", null);
|
|
context.Response.ContentType = "application/json; charset=utf-8";
|
|
// 将异常信息写入 HTTP 响应
|
|
await context.Response.WriteAsync(baseResponse.ToString());
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
_logger.LogError(context.Request.Path.ToString(), ex, "异常记录");
|
|
// 设置 HTTP 响应状态码为 500
|
|
context.Response.ContentType = "application/json; charset=utf-8";
|
|
context.Response.StatusCode = StatusCodes.Status200OK;
|
|
BaseResponse<object> baseResponse = new BaseResponse<object>(ResponseCode.Error, ex.Message, null);
|
|
// 将异常信息写入 HTTP 响应
|
|
await context.Response.WriteAsync(baseResponse.ToString());
|
|
}
|
|
finally
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|
|
}
|