Exception handler for REST controller in spring

允我心安 提交于 2019-12-07 23:46:09

问题


I want to handle exceptions so the URL information is automatically shown to the client. Is there an easy way to do this?

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

回答1:


You have two choices:

Spring Reference 15.9.1 HandlerExceptionResolver

Spring HandlerExceptionResolvers ease the pain of unexpected exceptions that occur while your request is handled by a controller that matched the request. HandlerExceptionResolvers somewhat resemble the exception mappings you can define in the web application descriptor web.xml. However, they provide a more flexible way to handle exceptions. They provide information about which handler was executing when the exception was thrown. Furthermore, a programmatic way of handling exceptions gives you more options for responding appropriately before the request is forwarded to another URL (the same end result as when you use the servlet specific exception mappings).

The HandlerExceptionResolver has one method, containing everything you need:

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

Or if you need different handlers for different controllers: Spring Reference Chapter 15.9.2 @ExceptionHandler

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

Short question short answer




回答2:


I'm doing the following trick:

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

Works flawless.



来源:https://stackoverflow.com/questions/8178319/exception-handler-for-rest-controller-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!