2011-11-18 73 views
2

我想处理异常,以便URL信息自动显示给客户端。是否有捷径可寻?春季REST控制器的异常处理程序

<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver"> 
    <!-- what property to set here? --> 
</bean> 

回答

3

你有两个选择:

Spring Reference 15.9.1 HandlerExceptionResolver

春天了HandlerExceptionResolvers缓解,而你的请求是由控制器 匹配请求处理时发生意外 异常的痛苦。 HandlerExceptionResolvers有点类似 异常映射,您可以在Web应用程序 描述符web.xml中定义异常映射。但是,它们提供了一种更灵活的方式来处理 异常。它们提供有关在抛出异常时执行哪个处理程序 的信息。此外,在将请求转发到另一个URL(与使用特定于servlet的异常映射相同的最终结果)之前,处理异常的编程方式为您提供了更多用于响应 的选项。

HandlerExceptionResolver有一个方法,包含你需要的一切:

HandlerExceptionResolver.resolveException(HttpServletRequest request, 
       HttpServletResponse response, 
       Object handler, Exception ex) 

或者,如果你需要不同的控制器不同的处理程序:Spring Reference Chapter 15.9.2 @ExceptionHandler

@ExceptionHandler(IOException.class) 
public String handleIOException(IOException ex, HttpServletRequest request) { 
    return "every thing you asked for: " + request; 
} 

短缺问题简答

+0

引用中的处理程序主题在这里:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers –

1

我是doin g以下绝招:

@ExceptionHandler(Exception.class) 
     public ModelAndView handleMyException(Exception exception) { 
     ModelAndView mv = new ModelAndView("redirect:errorMessage?error="+exception.getMessage()); 
     return mv; 
       } 

    @RequestMapping(value="/errorMessage", method=RequestMethod.GET) 
    @Responsebody 
    public String handleMyExceptionOnRedirect(@RequestParamter("error") String error) { 
    return error; 
      } 

作品完美无缺。