我正在尝试返回 Spring Boot 的默认响应,但我想记录我编写的异常:
@RestControllerAdvice
public class ExceptionControllerAdvice {
private final Logger logger = LoggerFactory.getLogger(CalculatorController.class);
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public Map<String, Object> handleMediaTypeNotAcceptableException(HttpMediaTypeNotAcceptableException ex, WebRequest request) {
DefaultErrorAttributes error = new DefaultErrorAttributes();
return error.getErrorAttributes(request, ErrorAttributeOptions.defaults());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Map<String, Object> handleException(Exception ex, WebRequest request) {
logger.error("Exception: ", ex);
DefaultErrorAttributes error = new DefaultErrorAttributes();
return error.getErrorAttributes(request, ErrorAttributeOptions.defaults());
}
当我不进入
@RestControllerAdvice
时,org.springframework.boot.web.servlet.error.DefaultErrorAttributes.getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options)
的路径和状态已正确设置,但是当我在控制器建议中发现异常时,它们为空,这些是状态和路径的正确读取:
this.getAttribute(requestAttributes, "jakarta.servlet.error.status_code");
this.getAttribute(requestAttributes, "jakarta.servlet.error.request_uri");
有人知道如何返回标准错误消息吗?我只想记录异常
这里我们有一个接近问题的问题,您可以找到适合您的答案和解决方案:https://stackoverflow.com/a/64138232/2556249 要保留标准错误消息,您需要手动向 WebRequest 属性添加值。
@RestControllerAdvice 公共类 ExceptionControllerAdvice { 私人最终记录器记录器 = LoggerFactory.getLogger(CalculatorController.class);
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public Map<String, Object> handleMediaTypeNotAcceptableException(HttpMediaTypeNotAcceptableException ex, WebRequest request) {
// Here you add error status code
webRequest.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, HttpStatus.BAD_REQUEST.value(), RequestAttributes.SCOPE_REQUEST);
// Here we add request URI and this could be a bit tricky
webRequest.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, ((ServletWebRequest)request).getRequest().getRequestURI(), RequestAttributes.SCOPE_REQUEST);
DefaultErrorAttributes error = new DefaultErrorAttributes();
return error.getErrorAttributes(request, ErrorAttributeOptions.defaults());
}
}
当我面对这些问题时,我开始阅读:https://github.com/spring-projects/spring-framework/issues/30828,然后浏览了十亿个链接。据我了解这个问题,只有将请求传递给嵌入式
/error
控制器时,才会填充这些字段。