3

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>

2 Answers 2

5

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

1
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.