我的要求是覆盖 HTTP 返回的状态代码(如 404、503 等)的响应。
我有我的公平份额搜索关于覆盖和发送 HTTP 状态代码的自定义错误响应,但所有这些答案都是针对我的资源内部发生的情况的自定义异常处理。我正在寻找一种方法来覆盖 HTTP 发送的默认响应,以防出现 404 之类的情况
{
"timestamp": "2024-03-05T17:15:57.389+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/api/v1/search"
}
例如:假设我的资源类似于上面的/api/v1/search,但在我的邮递员中我拼写错误,如/api/v1/sear
HTTP 的响应将如上所示。我想覆盖并返回此 HTTP 响应,例如
{
"code": "404",
"message": "Resource Not Found or check your spelling",
}
您可以使用@RestControllerAdvice并为此异常定义模型。
例如:
@RestControllerAdvice
public class ApplicationExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ResourceNotFoundException.class)
public ExceptionHandlerResponse handleResourceNotFoundException(ResourceNotFoundException exception,
HttpServletRequest request) {
HttpStatus httpStatus = HttpStatus.NOT_FOUND;
return ExceptionHandlerResponse.builder()
.code(httpStatus.value())
.message(exception.getMessage())
.build();
}