QuickApi异常规范化返回
vipwan opened this issue · 2 comments
vipwan commented
public interface IQuickApiExceptionResultBuilder
{
/// <summary>
/// 规范化返回异常
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
Task<IResult> ErrorResult(Exception exception);
}
vipwan commented
默认异常会返回规范化的错误信息
StatusCode = 500
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",
"title": "An error occurred while processing your request.",
"status": 500,
"detail": "The method or operation is not implemented."
}
个性化的错误返回:
/// <summary>
/// 自定义异常返回结果
/// </summary>
public class CustomExceptionResultBuilder : IQuickApiExceptionResultBuilder
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CustomExceptionResultBuilder(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Task<IResult> ErrorResult(Exception exception)
{
return Task.FromResult<IResult>(TypedResults.Json(new
{
Status = 500,
CurrentUser = _httpContextAccessor.HttpContext?.User?.Identity?.Name,
Exception = new
{
Message = exception.Message,
StackTrace = exception.StackTrace,
}
}));
}
}
//AddBiwenQuickApis
builder.Services.AddBiwenQuickApis();
//注册服务
builder.Services.AddSingleton<IQuickApiExceptionResultBuilder, CustomExceptionResultBuilder>();
StatusCode = 200
{
"status": 500,
"currentUser": "vipwan@ms.co.ltd",
"exception": {
"message": "The method or operation is not implemented.",
"stackTrace": " at Biwen.QuickApi.DemoWeb.Apis.ThrowErrorApi.ExecuteAsync(EmptyRequest request) in C:\\Users\\vipwa\\source\\repos\\Biwen.QuickApi\\Biwen.QuickApi.DemoWeb\\Apis\\CustomApi.cs:line 84\r\n at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)\r\n at Biwen.QuickApi.ServiceRegistration.RequestHandler(IHttpContextAccessor ctx, Type apiType, QuickApiAttribute quickApiAttribute) in C:\\Users\\vipwa\\source\\repos\\Biwen.QuickApi\\Biwen.QuickApi\\ServiceRegistration.cs:line 300"
}
}
vipwan commented
如果需要记录或者执行其他操作 可以实现IQuickApiExceptionHandler并注册 :
public class CustomExceptionHandler : IQuickApiExceptionHandler
{
private readonly ILogger<CustomExceptionHandler> _logger;
public CustomExceptionHandler(ILogger<CustomExceptionHandler> logger)
{
_logger = logger;
}
public Task HandleAsync(Exception exception)
{
_logger.LogError(exception, "QuickApi异常");
return Task.CompletedTask;
}
}
//注册服务
builder.Services.AddScoped<IQuickApiExceptionHandler, CustomExceptionHandler>();