SteelReed

Search

Search posts, questions…

5. Spring Boot

Custom exceptions and centralized error handling in Spring Boot: @RestControllerAdvice, ProblemDetail, validation

Designing custom exceptions with error codes, why try-catch in every controller is a bad idea, @RestControllerAdvice and @ExceptionHandler, ProblemDetail (RFC 9457), designing error responses, and DTO validation with Bean Validation.

17 Nov 20268 min readMid

–

Part 1 covered exceptions in core Java. This post answers: which exception describes a business error, where you catch it, and what the client gets back; that is, custom exceptions with error codes, @RestControllerAdvice, ProblemDetail and Bean Validation.

1. The problem

50 endpoints, each with its own try-catch: some return {"error": "..."}, some a plain string, and one returns e.getMessage() verbatim, SQL and table names included. The mobile app compares message strings to detect "email taken", and breaks when the backend fixes a typo.

2. Key idea

The controller is a front-desk clerk who only passes complaints upward; @RestControllerAdvice is the single customer-care office answering in one template. Error codes must be stable: clients branch on them, while messages may change or be translated.

Kind Thrown by Examples Log
Business exception your logic, on purpose email taken, insufficient balance WARN/INFO
System exception frameworks, libraries, infrastructure DB timeout, NPE ERROR + stack trace + alert
Status When
400 invalid data
401 / 403 not authenticated / not permitted
404 / 409 resource missing / state conflict
422 well-formed but violates business rules (team choice)
500 / 503 server error / an external dependency is down

2.1 Common traps

Trap Effect Fix
Checked custom exceptions @Transactional commits on error unchecked, or rollbackFor = Exception.class
Declaring private String message in the exception shadows Throwable's field, getMessage() returns null call super(message)
A catch-all @ExceptionHandler(Exception.class) swallows @PreAuthorize's AccessDeniedException, turning 403 into 500 a handler that rethrows security errors
@Size(min = 10) without @NotBlank null passes add @NotNull/@NotBlank
existsByUsername then insert two concurrent requests both pass a UNIQUE constraint, mapping DataIntegrityViolationException to 409

401/403 raised in the filter chain (missing token, URL rules) never reach @ControllerAdvice: write an AuthenticationEntryPoint and AccessDeniedHandler returning the same format.

3. In Java

JAVA
public enum ErrorCode {
    USER_EMAIL_TAKEN(HttpStatus.CONFLICT, "The email is already registered"),
    USER_NOT_FOUND(HttpStatus.NOT_FOUND, "User not found");
    final HttpStatus status; final String message;
    ErrorCode(HttpStatus s, String m) { status = s; message = m; }
}
 
public class BusinessException extends RuntimeException {    // unchecked: rolls back by default
    final ErrorCode code;
    public BusinessException(ErrorCode code) { super(code.message); this.code = code; }
}
 
@RestControllerAdvice
class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    ProblemDetail business(BusinessException e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(e.code.status, e.getMessage());
        p.setProperty("code", e.code.name());                  // clients branch on code
        p.setProperty("traceId", Span.current().getSpanContext().getTraceId());
        return p;                                              // application/problem+json
    }
}
// 409 {"title":"Conflict","detail":"The email is already registered","code":"USER_EMAIL_TAKEN",...}

Validation errors: override handleMethodArgumentNotValid (declaring another @ExceptionHandler for it fails startup as Ambiguous). Since Spring 6.1, constraints on @PathVariable/@RequestParam run built in and throw HandlerMethodValidationException (400). Other languages: NestJS has exception filters; ASP.NET Core ships ProblemDetails.

Where to validate
Layer Checks
DTO (Bean Validation) shape: @NotBlank, @Size, @Email, @Pattern, @Valid for nested objects
Service business rules: is the username taken?
Database NOT NULL, UNIQUE, FK, CHECK: the last line of defense

spring-boot-starter-validation hasn't been bundled with starter-web since Boot 2.3. @Valid on service method parameters needs @Validated on the class for a proxy; internal calls (this.create(...)) skip validation. A BindingResult in the controller allows per-endpoint tweaks but repeats like try-catch; by default, let errors flow to the global handler.

4. Working with AI

Give the AI: an error-code enum from the business error list, the global handler, @WebMvcTest tests for each error code.

Check in AI-written code:

  • No try-catch in controllers to build error responses by hand.
  • Error responses contain no stack traces, SQL or class names; they carry code and traceId.
  • Custom exceptions are unchecked and call super(message) (and super(message, cause)).
  • The Exception.class catch-all doesn't swallow AccessDeniedException/AuthenticationException.
  • Every "create if missing" has a UNIQUE constraint in the DB.

5. Exercises

Exercise 1: A bank account

Write BankAccount (username, password, balance) with two custom exceptions: a checked one when withdrawing more than the balance, an unchecked one when the password is shorter than 6 characters. main catches both and always prints "Transaction finished." The task calls the checked exception NegativeBalanceException; is that a good name?

Solution to Exercise 1
  • InvalidPasswordException extends RuntimeException: thrown in the constructor; the caller passed bad input.
  • InsufficientBalanceException extends Exception: thrown in withdraw(amount) when amount > balance; the caller must handle it (e.g. ask for another amount).
  • main: try { ... } catch (InsufficientBalanceException e) { ... } catch (InvalidPasswordException e) { ... } finally { System.out.println("Transaction finished."); }.
  • The name: the balance never goes negative; what's missing is money, so InsufficientBalanceException is more accurate. Also check amount <= 0 (IllegalArgumentException) and use BigDecimal for money.
  • In Spring, both become unchecked BusinessExceptions with error codes, so @Transactional rolls back and the global handler returns 409/400.

Exercise 2: An AI-written handler

The AI adds @ExceptionHandler(Exception.class) ProblemDetail all(Exception e) { return ProblemDetail.forStatusAndDetail(INTERNAL_SERVER_ERROR, e.getMessage()); } to the advice, described as "catches everything, clients always get JSON". Afterwards a @PreAuthorize endpoint returns 500 for users lacking permission, and a DB error returns the SQL. How do you fix it?

Solution to Exercise 2
  • 403 becomes 500: @PreAuthorize throws AccessDeniedException inside the controller call, and the catch-all swallows it. Add handlers for AccessDeniedException and AuthenticationException that rethrow (throw e) so Spring Security returns 403/401.
  • Leaked SQL: a system exception's e.getMessage() contains internals. The catch-all returns a generic message ("Internal error") plus traceId; the details and stack trace go to an ERROR log.
  • Tests: a @WebMvcTest with an unauthorized user expecting 403; a simulated DataAccessException expecting a body without select.

Summary

  • Business errors are unchecked and carry stable error codes.
  • One @RestControllerAdvice returns ProblemDetail; controllers don't try-catch.
  • Never return stack traces or SQL; clients get code and traceId.
  • Filter and Spring Security errors need their own entry points.
  • Constraints treat null as valid; a UNIQUE constraint is what truly stops races.

Read more: DTOs, responses and validation for REST APIs.

Practice interview questions on this topic

All Web & REST API questions →All Spring Boot questions →All Transactions & Locking questions →

Loading comments…
Next on the roadmapCommon Spring Boot errors and how to debug them: from port conflicts to a 403 that became a 500