【发布时间】:2021-12-03 09:26:36
【问题描述】:
我正在使用库 Microsoft.AspNetCore.Http 和 Microsoft.AspNetCore.Mvc。我也在使用 Identity 的 JWT 令牌。
令牌过期后,API 会抛出 http 401 错误,如果声明错误,则返回 http 403 错误。
我需要能够捕捉这两个雕像并将它们包装成我统一的错误消息格式
public class ErrorMessage
{
public int httpStatus { get; set; }
public string Header { get; set; } = "Error";
public string Message { get; set; }
}
我的标准 API 格式
[Authorize]
[HttpPost]
[Route("Logout")]
public async Task<IActionResult> Logout()
{
try
{
....
}
catch (Exception e)
{
_logger.LogError($"Error in {nameof(Login)}: {e}");
return BadRequest(new ErrorMessage { httpStatus = 500, Message = e.Message });
}
}
【问题讨论】:
-
这些异常是由在控制器操作之前执行的其他中间件引发的。所以尝试 catch 是行不通的。一般来说,您需要编写一个middleware 并拦截其中的异常。
标签: c# asp.net-core asp.net-core-webapi