【发布时间】:2013-07-02 10:01:47
【问题描述】:
我有一个 Spring 3.2 应用程序,并且我创建了一个基于 Spring MVC 的 REST API。我正在使用 @ControllerAdvice 注释进行自定义异常处理。例如:
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
@ExceptionHandler(MyCustomException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ExceptionMessage handleMyCustomException(MyCustomException ex){
return new ExceptionMessage(ex.getClass().getName(), ex.getMessage(), ex.getExceptionCode());
}
}
问题是我看到我的自定义异常是如何被抛出的,但异常处理程序方法实际上没有被执行,因此我的异常消息没有返回给客户端。相反,我在日志中注意到 DefaultHandlerExceptionResolver 如何处理异常(使用 Spring 通用异常,ServletRequestBindingException 在 GET 方法中)。我怎样才能摆脱这个问题?
谢谢!
【问题讨论】:
-
RestResponseEntityExceptionHandler的包是否列在component-scan base-package属性中? -
@zeroflagL 是的,是
-
等一下,
ServletRequestBindingException?听起来您的异常是在调用处理程序方法之前引发的。 -
你是对的@zeroflagL,我没有注意到我的 API 调用测试过程中缺少一些请求参数。如果您添加您的评论作为答案,我会很高兴地接受它!
标签: spring spring-mvc