因此,我试图以通用方式记录 Spring 项目的 Controller 返回的所有未捕获的异常。
我能够使用以下异常处理程序做到这一点:
@ControllerAdvice
public class ControllerConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void handleBadRequest(HttpMessageNotReadableException e) {
logger.warn("Returning HTTP 400 Bad Request", e);
throw e;
}
@ExceptionHandler(AccessDeniedException.class)
public void defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
logger.error("Error in request:" + request.getRequestURL(), e);
throw e;
}
这也会返回请求的错误响应,因此我不必区分所有不同的错误响应代码。
但是,对于该方法的每次调用,都会因为该方法中抛出的异常而创建第二个错误日志:
代码来自 org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#doResolveHandlerMethodException
try {
if (logger.isDebugEnabled()) {
logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
}
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception);
}
catch (Exception invocationEx) {
if (logger.isErrorEnabled()) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
}
return null;
}
那么有没有更聪明的方法来返回方法的原始异常?
最佳答案
这取决于您所说的“返回原始异常的更智能方法”是什么意思。您究竟想返回给客户什么?如果这只是异常的消息,您可以简单地从异常处理程序返回它并使用 @ResponseBody
注释该方法。 . Spring 会为您完成剩下的工作。
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleBadRequest(HttpMessageNotReadableException e) {
logger.warn("Returning HTTP 400 Bad Request", e);
throw e.getMessage();
}
您还可以返回一些自定义对象,这些对象包装异常信息和您想要的任何其他数据。
关于Spring异常处理程序记录所有异常但返回原始响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339604/