2016-05-20 83 views
2

所以我想以通用的方式记录所有由spring项目的控制器返回的未捕获的异常。 我可以用下面的异常处理程序来做到这一点:Spring异常处理程序记录所有异常,但返回原始响应

@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; 
    } 

那么是否有更聪明的方法来返回方法的原始异常?

回答

0

这取决于你是什么意思的“更聪明的方式来返回原始异常”。你想要什么回到客户端?如果这只是异常的消息,您可以简单地将它从异常处理程序中返回并用@ResponseBody注释该方法。春天会为你休息。

@ExceptionHandler(HttpMessageNotReadableException.class) 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
@ResponseBody 
public String handleBadRequest(HttpMessageNotReadableException e) { 
    logger.warn("Returning HTTP 400 Bad Request", e); 
    throw e.getMessage(); 
} 

您还可以返回一些包装异常信息和您需要的其他数据的自定义对象。