fastcodejava
fastcodejava

Reputation: 41097

Exception handler for REST controller in spring

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>

Upvotes: 3

Views: 9512

Answers (2)

Ralph
Ralph

Reputation: 120771

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

Upvotes: 5

danny.lesnik
danny.lesnik

Reputation: 18639

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.

Upvotes: 1

Related Questions