
# @ControllerAdvice

`@ControllerAdvice()` marks a bean whose `@ExceptionHandler` methods answer errors for every controller of the application. `@RestControllerAdvice()` is the same.

## Why

An error such as `BookNotFoundException` can come from many controllers. Writing the same `@ExceptionHandler` in each of them repeats the code and lets the answers drift apart. An advice bean holds the handlers once, for all controllers. It also sees the errors that no controller can: a path that nothing maps (404), a wrong method (405), an `Accept` or `Content-Type` nobody handles (406, 415), and the errors of WebSocket handshakes.

Narrow an advice when different parts of the application answer differently, for example an admin API with more detail than the public one.

## Example

```dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

class BookNotFoundException implements Exception {
  BookNotFoundException(this.isbn);

  final String isbn;
}

class AdminOnly {
  const AdminOnly();
}

abstract class ReportController {}

// For every controller. Ranked first among the advice beans.
@RestControllerAdvice()
@Order(1)
class ApiErrors {
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.notFound)
  ProblemDetail notFound(BookNotFoundException e) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No book ${e.isbn}')
        ..setProperty('isbn', e.isbn);

  // Unknown paths: a hint where the documentation is.
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.notFound)
  ProblemDetail unknown(NoHandlerFoundException e) =>
      ProblemDetail.forStatusAndDetail(
        HttpStatus.notFound,
        'No ${e.path}; see https://shop.example/api-docs',
      );
}

// Only the controllers of the libraries under package:shop/admin/.
@RestControllerAdvice.of(basePackages: ['package:shop/admin/'])
class AdminErrors {
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.conflict)
  ProblemDetail conflict(StateError e) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.conflict, e.message);
}

// Controllers of a type or its subtypes, or with an annotation.
@ControllerAdvice.of(
  name: 'reportErrors',
  assignableTypes: [ReportController],
  annotations: [AdminOnly],
)
class ReportErrors {
  @ExceptionHandler()
  @ResponseStatus(HttpStatus.badRequest)
  ProblemDetail invalid(ArgumentError e) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.badRequest, '${e.message}');
}
```

## Parameters

`@ControllerAdvice([name])` and `@RestControllerAdvice([name])`: an advice for every controller.

| Name | Type | Default | Meaning |
|---|---|---|---|
| `name` (positional) | `String?` | `null` | The bean name. `null`: the class name in lowerCamelCase. |

`@ControllerAdvice.of(...)` and `@RestControllerAdvice.of(...)`: an advice for some controllers. A controller that matches any of the lists is advised.

| Name | Type | Default | Meaning |
|---|---|---|---|
| `name` | `String?` | `null` | The bean name. |
| `basePackages` | `List<String>` | `const []` | Prefixes of the library URI where the controller is declared, such as `package:shop/admin/` (Spring's `basePackages`, with Dart library URIs instead of Java packages). |
| `assignableTypes` | `List<Type>` | `const []` | The controllers of these types, or of a type that implements or extends one of them. |
| `annotations` | `List<Type>` | `const []` | The controllers whose class carries an annotation of one of these exact types, such as `RestController`; an annotation that extends a listed one does not match. |

With all three lists empty, `.of` advises every controller, as the short form does.

## Rules

- **An advice is a bean.** `@ControllerAdvice` extends `@Component`, so the class is created and injected like any other bean; it can take services through its constructor.
- **Only its `@ExceptionHandler` methods count.** Other methods are ignored. The handler methods follow the rules of [@ExceptionHandler](exception-handler.md): their parameters, results and `@ResponseStatus`.
- **`@RestControllerAdvice` and `@ControllerAdvice` behave the same.** Every advice writes its handlers' results as the body, since there are no views. `@RestControllerAdvice` exists so that code written for Spring reads the same.
- **The controller's own handlers come first.** An advice answers what the controller's handlers leave.
- **Order.** The advice beans are tried in `@Order` (lowest first; without `@Order`, last; equal orders keep the order of registration). The first bean that applies to the controller and has a handler for the error answers it, even when a later bean has a more specific handler, as in Spring. Within one bean, the most specific handler wins.
- **Narrowed advice and errors without a controller.** An advice narrowed with `.of` does not see errors raised before a controller method was chosen (404, 405, 406, 415, the 400 of unmet header conditions) nor the errors of other handler mappings, as in Spring.
- **Errors thrown by a filter** reach no advice.
- **`HandlerExceptionResolver` beans** are asked only when no advice (and no controller handler) answers (see [HandlerExceptionResolver](handler-exception-resolver.md)).

## In Spring (Java)

```java
@RestControllerAdvice
@Order(1)
class ApiErrors {
  @ExceptionHandler
  @ResponseStatus(HttpStatus.NOT_FOUND)
  ProblemDetail notFound(BookNotFoundException e) { ... }
}

@RestControllerAdvice(basePackages = "com.shop.admin")
class AdminErrors { ... }
```

Differences that matter:

- **`basePackages` takes library URI prefixes** (`package:shop/admin/`) instead of Java packages. There is no `basePackageClasses`.
- **`annotations` match the exact annotation type** of the controller, not annotations meta-annotated with it.
- Attributes other than the name need the `.of` constructor.
- `@ControllerAdvice` in Spring also carries `@InitBinder` and `@ModelAttribute` methods; here only `@ExceptionHandler` methods exist.

## See also

- [@ExceptionHandler](exception-handler.md)
- [HandlerExceptionResolver](handler-exception-resolver.md)
- [Errors](index.md)
- [@Component](../../spring-core-dart/beans/component.md)
