title: ExceptionHandler in Spring
body: <pre><code>import org.springframework.beans.TypeMismatchException;
  import javax.annotation.*;
  import javax.servlet.http.*;
  import org.springframework.http.HttpStatus;
  import org.springframework.stereotype.Controller;
  import org.springframework.context.annotation.Scope;
  import org.springframework.web.bind.annotation.*;
  
  @Controller
  @RequestMapping(value = "/aa")
  public class BaseController {
  
      @RequestMapping(value = "/bb/{number}", method = RequestMethod.GET, produces = "plain/text")
      public void test(@PathVariable final double number, final HttpServletResponse response) throws IOException {
          throw new MyException("whatever");
      }
  
      @ResponseBody
      @ExceptionHandler(MyException.class)
      public MyError handleMyException(final MyException exception, final HttpServletResponse response) throws IOException {
          ...
      }
  
      @ResponseBody
      @ExceptionHandler(TypeMismatchException.class)
      public MyError handleTypeMismatchException(final TypeMismatchException exception, final HttpServletResponse response) throws IOException {
          ...
      }
  
      @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
      @ResponseBody
      @ExceptionHandler
      public MyError handleException(final Exception exception) throws IOException {
          ...
      }
  }
  </code></pre>
  
  <p>If I call <a href="http://example.com/aa/bb/20" rel="noreferrer">http://example.com/aa/bb/20</a>
  the function handleMyException is executed, as expected.</p>
  
  <p>However, if I call <a href="http://example.com/aa/bb/QQQ" rel="noreferrer">http://example.com/aa/bb/QQQ</a>
  I would expect that the function <code>handleTypeMismatchException</code> is called,
  but instead, handleException is called, with exception of type <code>TypeMismatchException</code>.</p>
  
  <p>a nasty workaround to make it would would be to test the type of exception inside <code>handleException()</code>,
  and call <code>handleTypeMismatchException</code> if the exception is of type <code>TypeMismatchException</code>.</p>
  
  <p>but why does it now work?
  the exceptionhandler is chosen at runtime according to the type of exception?
  or it is chosen at compile time?</p>