title: Spring: Different exception handler for RestController and Controller
body: <p>In Spring you can set up "global" exception handler via @ControllerAdvice and @ExceptionHandler annotation. I'm trying to utilize this mechanism to have two global exception handlers:</p>
  
  <ul>
  <li><code>RestControllerExceptionHandler</code> - which should return error responses as json for any controller annotated with <code>@RestController</code></li>
  <li><code>ControllerExceptionHandler</code> - which should print error message to the screen for any other controller (annottated with <code>@Controller</code>)</li>
  </ul>
  
  <p>The problem is that when I declare these two exception handlers spring always uses the <code>ControllerExceptionHandler</code> and never <code>RestControllerExceptionHandler</code> to handle the exception.</p>
  
  <p>How to make this work ? 
  BTW: I tried to use @Order annotation but this does not seem to work.</p>
  
  <p>Here are my exception handlers:</p>
  
  <pre><code>// should handle all exception for classes annotated with         
  @ControllerAdvice(annotations = RestController.class)
  public class RestControllerExceptionHandler {
  
  
    @ExceptionHandler(Exception.class)
    public ResponseEntity&lt;ErrorResponse&gt; handleUnexpectedException(Exception e) {
  
      // below object should be serialized to json
      ErrorResponse errorResponse = new ErrorResponse("asdasd"); 
  
      return new ResponseEntity&lt;ErrorResponse&gt;(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  // should handle exceptions for all the other controllers
  @ControllerAdvice(annotations = Controller.class)
  public class ControllerExceptionHandler {
  
  
    @ExceptionHandler(Exception.class)
    public ResponseEntity&lt;String&gt; handleUnexpectedException(Exception e) {
      return new ResponseEntity&lt;String&gt;("Unexpected exception, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  
  }
  }
  </code></pre>
  
  <p>When I remove <code>ControllerExceptionHandler</code> than <code>RestControllerExceptionHandler</code> is correctly called by spring (only for classes annotated with <code>@RestController</code>).... but when I add <code>ControllerExceptionHandler</code> than all goes via <code>ControllerExceptionHandler</code>. Why? </p>