BBackend CourseLeroy Labs
0/0
Search the course

Global error handling, error codes & response envelopes

@RestControllerAdvice, a consistent ApiError shape, machine-readable error codes, correlation ids, i18n messages, and whether to wrap successes in an envelope.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

Every error a client sees should have the same shape, a correct status code, a stable machine-readable code and no internals (stack traces, SQL).

public record ApiError(
    Instant timestamp, int status, String error, String message,
    Map<String, List<String>> details,   // field -> messages
    ErrorCode code,                        // e.g. ROOM_FULL, VALIDATION_FAILED
    String correlationId) {}               // lets support find the log line

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<ApiError> validation(MethodArgumentNotValidException ex) {
        var details = ex.getBindingResult().getFieldErrors().stream()
            .collect(groupingBy(FieldError::getField, mapping(FieldError::getDefaultMessage, toList())));
        return build(HttpStatus.BAD_REQUEST, "Validation failed", details, ErrorCode.VALIDATION_FAILED);
    }

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    ResponseEntity<ApiError> conflict(Exception ex) {
        return build(HttpStatus.CONFLICT, "This record was changed by someone else. Reload and retry.",
                     null, ErrorCode.CONCURRENT_UPDATE);
    }

    @ExceptionHandler(Exception.class)            // last resort
    ResponseEntity<ApiError> unexpected(Exception ex) {
        log.error("Unhandled", ex);               // full detail in logs only
        return build(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong", null, ErrorCode.INTERNAL);
    }
}

Domain exceptions

Throw meaningful exceptions from services and map them in one place:

public class RoomFullyOccupiedException extends RuntimeException { /* ... */ }
// handler: RoomFullyOccupiedException -> 409 ROOM_FULL

In your projects

Hostel-Web-Appshared/exception/GlobalExceptionHandler.java

ApiError(timestamp, status, error, message, fieldErrors, ErrorCode):

  • VALIDATION_FAILED returns 400.
  • Room full, booking already exists and invalid transition return 409.
  • PaymentFailedException returns 402.
  • DisabledException returns 403.
  • The catch-all returns 500.

Success responses are wrapped in ApiResponse<T>(timestamp, success, message, data) with @JsonInclude(NON_NULL).

SperoTek (in dev)shared/web/GlobalExceptionHandler.java · ApiError · ErrorCode

SperoTek handles ApiException, ConstraintViolationException, type mismatches, EntityNotFoundException, optimistic-lock conflicts, auth and access-denied, plus a catch-all. ApiError carries a correlationId taken from the MDC, so a user can quote it in a support ticket. Spring Security failures are written in the same JSON shape by SecurityErrorWriter, because they happen before the controller advice can see them.

IR3D (Kontentt)shared/exception/ApiError.java · ApiErrorController · i18n/messages*.properties

IR3D translates error details through i18n (messages.properties, messages_fr.properties), so exceptions carry keys like "error.linkPreviewRateLimited". An ApiErrorController handles /error, which Spring uses for errors outside MVC. ErrorShapeIntegrationTest tests the error contract.

Report-Manager-2shared/exception/GlobalExceptionHandler.java

RM deliberately ignores client-disconnect and SSE errors (a broken pipe when a browser closes the tab). Logging those as 500s would flood Sentry.

Alternatives

Option Notes
Custom ApiError record (yours) Full control
RFC 9457 Problem Details (ProblemDetail in Spring 6+) A standard: type, title, status, detail, instance, plus extensions. Enable with spring.mvc.problemdetails.enabled=true. Worth knowing for interviews and public APIs
ResponseStatusException Quick one-offs; scatters status codes around
@ResponseStatus on exception classes Simple, but no body customisation

Envelope or no envelope?

Wrap successes (ApiResponse in Hostel and SperoTek) Return the bare resource (Store)
Consistent client parsing, room for metadata HTTP already has status and headers; less nesting
Can tempt you into 200 {"success": false} (don’t) Matches most public APIs (Stripe, GitHub)

Either works if you are consistent. Never put failures inside a 200.

  • Error codes vs messages. Messages are for humans and can change or be translated. Codes are for programs and must stay stable.
  • Don’t leak. Don’t reveal stack traces, SQL or “user exists”. Hostel’s password reset gives the same reply for unknown emails, which prevents account enumeration.
  • Retry hints. Send Retry-After on 429 and 503. SperoTek exposes it through CORS.
  • Filter-level errors. Errors thrown in filters (JWT, rate limit) never reach @ControllerAdvice, so they must write the JSON themselves. Hostel’s RateLimitingFilter writes an ApiError with 429.

Check yourself

1. Why does SperoTek need SecurityErrorWriter in addition to GlobalExceptionHandler?
2. Which is the IETF standard error format supported by Spring?