SteelReed

Search

Search posts, questions…

Spring BootQuestion 16 / 26

Junior

Why handle errors with @RestControllerAdvice instead of try-catch in every controller?

Short answer

@RestControllerAdvice turns exceptions into HTTP responses in one place: controllers hold only the happy path, and every endpoint returns errors in the same format. When several handlers match, Spring picks the closest exception type.

throws exceptionOrderNotFoundExceptionMethodArgumentNotValidExceptiongeneric ExceptionControllerhappy path only@RestControllerAdvice404 ProblemDetail400 with errors500, log ERROR

3 points to say:

  1. One advice, one error format for every endpoint; scattered try-catch leads to drifting formats, missed logs, even 200 with an error message.
  2. When several handlers match: the local handler wins, then the closest exception type in the hierarchy.
  3. Services throw unchecked custom exceptions with an error code; the generic Exception handler logs ERROR and returns 500 without details.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.