我正在尝试在我的项目中全局处理错误。我讨厌在每个端点都进行 try-catch 的想法。
我有以下测试端点:
public sealed class Endpoint(SepukuDbContext dbContext, IJwtTokenService jwtTokenService, IUserAuthorizationService userAuthorizationService) : Endpoint<Request>
{
public override async Task HandleAsync(Request req, CancellationToken ct)
{
var user = await dbContext.Users.Where(x => x.Email == req.Email).Select(x => x).SingleOrDefaultAsync(ct);
if (user is null)
{
ThrowError("The supplied credentials are invalid!");
return;
}
if (userAuthorizationService.IsAuthorized(user, req.Password))
{
await SendAsync(
new
{
Username = user.Name,
Token = jwtTokenService.GetToken(user),
});
}
else
{
ThrowError("The supplied credentials are invalid!");
}
}
}
要测试错误处理,jwtTokenService.GetToken(user) 会抛出 InvalidDataException。 但是,端点返回 200 Response.Ok。为什么?
我添加了 app.UseDefaultExceptionHandler() 进行全局错误处理,但没有帮助。
首先,我尝试了在
SendAsync
内抛出异常的等效代码,它在 HTTP 响应上正确返回 500 ISE 错误。
尽管如此,以下是 ASP.NET 应用程序中错误处理的正确设置(也在使用 FastEndpoint 时):
// Our exception handler
public class ExceptionHandler : IExceptionHandler
{
public ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
return ValueTask.FromResult(true); // if exception is handled, false if not
}
}
和应用程序设置:
var builder = WebApplication.CreateBuilder();
builder.Services.AddFastEndpoints();
// Register our exception handler
builder.Services.AddExceptionHandler<ExceptionHandler>();
var app = builder.Build();
// Use exception handling middleware
app.UseExceptionHandler("/error");
app.UseFastEndpoints();
app.Run();