@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

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

In Spring (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:

See also