-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
QuickApi异常规范化返回 #10
Labels
Comments
默认异常会返回规范化的错误信息 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": "[email protected]",
"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"
}
} |
如果需要记录或者执行其他操作 可以实现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>(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
The text was updated successfully, but these errors were encountered: