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.
On this page
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
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
codeandtraceId. - Custom exceptions are unchecked and call
super(message)(andsuper(message, cause)). - The
Exception.classcatch-all doesn't swallowAccessDeniedException/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 inwithdraw(amount)whenamount > 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
InsufficientBalanceExceptionis more accurate. Also checkamount <= 0(IllegalArgumentException) and useBigDecimalfor money. - In Spring, both become unchecked
BusinessExceptions with error codes, so@Transactionalrolls 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:
@PreAuthorizethrowsAccessDeniedExceptioninside the controller call, and the catch-all swallows it. Add handlers forAccessDeniedExceptionandAuthenticationExceptionthat 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") plustraceId; the details and stack trace go to an ERROR log. - Tests: a
@WebMvcTestwith an unauthorized user expecting 403; a simulatedDataAccessExceptionexpecting a body withoutselect.
Summary
- Business errors are unchecked and carry stable error codes.
- One
@RestControllerAdvicereturnsProblemDetail; controllers don't try-catch. - Never return stack traces or SQL; clients get
codeandtraceId. - 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
- How do you design error responses for a multi-service system, and why not return stack traces to clients?
- Why handle errors with @RestControllerAdvice instead of try-catch in every controller?
- How do a servlet filter and a HandlerInterceptor differ? Does an exception in a filter reach @ControllerAdvice?
- What is check-then-act? Two requests both "create if missing" — how do you avoid duplicates?
All Web & REST API questions →All Spring Boot questions →All Transactions & Locking questions →
Comments
Community rules