83 lines
2.6 KiB
C#
83 lines
2.6 KiB
C#
using System.Net;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace SharpAbp.Infrastructure.Api.Middleware
|
|
{
|
|
public class GlobalExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<GlobalExceptionMiddleware> _logger;
|
|
|
|
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
|
|
{
|
|
_next = next;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await HandleExceptionAsync(context, ex);
|
|
}
|
|
}
|
|
|
|
private Task HandleExceptionAsync(HttpContext context, Exception ex)
|
|
{
|
|
if (ex is Common.BusinessException bizEx)
|
|
{
|
|
|
|
return WriteJsonResponse(context, Common.CommonResponseCodeEnum.Error, bizEx.Message);
|
|
}
|
|
|
|
if (ex is UnauthorizedAccessException)
|
|
{
|
|
|
|
return WriteJsonResponse(context, Common.CommonResponseCodeEnum.NoAuth, "未授权访问");
|
|
}
|
|
|
|
if (ex is ArgumentException argEx)
|
|
{
|
|
|
|
return WriteJsonResponse(context, Common.CommonResponseCodeEnum.ParamError, argEx.Message);
|
|
}
|
|
|
|
if (ex is TimeoutException || ex is OperationCanceledException)
|
|
{
|
|
|
|
return WriteJsonResponse(context, Common.CommonResponseCodeEnum.Error, "操作超时,请稍后重试: " + ex.Message);
|
|
}
|
|
|
|
_logger.LogError(ex, "系统异常: {Message}", ex.Message);
|
|
return WriteJsonResponse(context, Common.CommonResponseCodeEnum.Exception, ex.Message);
|
|
}
|
|
|
|
private static Task WriteJsonResponse(HttpContext context, Common.CommonResponseCodeEnum code, string message)
|
|
{
|
|
context.Response.StatusCode = 200;
|
|
context.Response.ContentType = "application/json";
|
|
return context.Response.WriteAsync(JsonConvert.SerializeObject(new
|
|
{
|
|
code = code,
|
|
info = message,
|
|
data = (object?)null
|
|
}));
|
|
}
|
|
}
|
|
|
|
public static class GlobalExceptionMiddlewareExtensions
|
|
{
|
|
public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
|
|
{
|
|
return app.UseMiddleware<GlobalExceptionMiddleware>();
|
|
}
|
|
}
|
|
}
|