我想为 spring boot 中的 400、401、405、403 和 500 错误发送自定义 JSON 响应。对于这些错误,spring boot 有时会发送一个 HTML 响应,有时是一个空的响应主体响应,有时是具有时间戳、异常、消息等的完整响应。我想要一个单一且一致的 JSON 响应来处理所有这些错误,就像这样
{
statusCode : 405,
message: "HTTP Method not allowed"
}
我已经使用 @ControllerAdvice
为很多异常发送自定义响应。我面对这些 400、401、405、403 和 500 错误的问题是,我不知道这些错误发生时会抛出哪些异常,因此我可以为它们编写 @ExceptionHandlers
。即使我不知道这种方式是否可行,即使可能也是实现它的正确方法。
有什么方法可以在 Spring boot 中实现吗?
最佳答案
所有传出异常都由 Spring Boot 使用 BasicErrorController
处理。
我们可以使用 Controller 建议处理/更改大部分异常消息。但是,在到达 Controller 之前抛出的异常,如 NotFound
、BadRequest
等,再次由 BasicErrorController
我们也可以通过覆盖 BasicErrorController
来改变它。
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
@Slf4j
public class BasicErrorControllerOverride extends AbstractErrorController {
public BasicErrorControllerOverride(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
Map<String, Object> errorCustomAttribute = new HashMap<>();
errorCustomAttribute.put("custome_message", "error");
errorCustomAttribute.put("custom_status_field", status.name());
return new ResponseEntity(errorCustomAttribute, status);
}
@Override
public String getErrorPath() {
return "/error";
}
}
错误消息现在将更改为如下所示
{
"custome_message": "UNAUTHORIZED",
"custom_status_field": "error"
}
关于java - 如何在 spring boot 中发送 400、401、405、403 和 500 错误的自定义响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62651277/