Background

In many real-world REST APIs, developers want to handle exceptions differently per controller (e.g., user-facing vs. admin APIs). While @ControllerAdvice is powerful, it is global or package-scoped, which can lead to tight coupling and handler bloat.

Proposed Feature

Introduce a simple way to annotate a controller with a custom exception handler delegate, like:

@UseExceptionHandler(UserExceptionHandler.class)
@RestController
@RequestMapping("/users")
public class UserController {
   ...
}

**Comment From: bclozel**

Thanks for raising this.

We are supporting already a few mechanism for choosing exception handlers.


First, directly in the controller:

```java
@RestController
@RequestMapping("/users")
public class UserController {

  @GetMapping("/{id})
  public User getUserById(@PathVariable String id) {
    //...
    throw new MissingUserException(id);
  }

  @ExceptionHandler
  public ResponseEntity<String> handleMissingUser(MissingUserException exception) {
    //...
  }
}

Or apply a controller advice on controllers annotated with @RestController (or any custom annotation!)

@ControllerAdvice(annotations = RestController.class)
public class RestControllerAdvice {

  @ExceptionHandler
  public ResponseEntity<String> handleMissingUser(MissingUserException exception) {
    //...
  }
}

Or apply a controller advice on controllers within a particular package:

@ControllerAdvice("org.example.users")
public class RestControllerAdvice {

  @ExceptionHandler
  public ResponseEntity<String> handleMissingUser(MissingUserException exception) {
    //...
  }
}

Or apply a controller advice on chosen controllers:

@ControllerAdvice(assignableTypes = {UserController.class, UserAdminController.class})
public class RestControllerAdvice {

  @ExceptionHandler
  public ResponseEntity<String> handleMissingUser(MissingUserException exception) {
    //...
  }
}

While your solution seems interesting, I think this would miss a critical part of our error handling support: being able to map to any exception in the type hierarchy (MissingUserException extends InvalidUserException for example), or mapping to any exception in the causes stack. See the reference documentation for more.

I'm declining this enhancement proposal since the existing support is quite extensive and supporting this additional feature would create conflicts: what if a @ControllerAdvice maps to a controller method with a more specific exception type than the one used by the @UseExceptionHandler annotation? How can we ensure that developers don't miss adding such annotations in their codebase? I think the complexity/improvement balance is not in favor of implementing this.

Thanks!