2013-07-04 164 views
0

我有一个Spring 3.2应用程序,我创建了一个基于Spring MVC的REST API。我正在使用@ControllerAdvice注释进行自定义异常处理。例如:Spring REST API自定义异常处理

@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通用的一种,GET方法中的ServletRequestBindingException)。我怎样才能摆脱这个问题?

谢谢!

+0

'component-scan base-package'属性中列出'RestResponseEntityExceptionHandler'包吗? – zeroflagL

+0

@zeroflagL是的,它是 – jarandaf

+1

等一下,'ServletRequestBindingException'?听起来像你的异常在处理器方法被调用之前抛出。 – zeroflagL

回答

0

ServletRequestBindingException暗示控制器的处理程序方法出错了。在这种情况下,一些绑定问题。

只有在控制器处理程序方法(@RequestMapping)内引发异常时,才会调用注解@ExceptionHandler的异常处理程序。

+1

有没有什么方法可以在自动公开的spring-data-rest端点中自定义异常处理? – Rafael