Custom exception handling with Spring's @ControllerAdvice

Modern APIs must turn failures into clear, consistent responses that mobile apps, payment services and support teams can act on. Otherwise, a missing order or invalid token can surface as an unhelpful 500 error with internal details attached.

Spring provides a focused way to centralise this behaviour. The JavaWhizz tutorials include related guidance on Spring APIs and practical integrations, while the pattern below keeps JSON error handling predictable and maintainable.

Why centralise exception handling

A controller should describe what succeeded and throw an exception when it cannot complete the request. Repeating try and catch blocks across every endpoint wastes effort and encourages inconsistent status codes, messages and payloads.

@RestControllerAdvice applies exception handlers across REST controllers, while @ControllerAdvice is the broader form used by MVC applications. For a JSON API, the REST variant is usually simpler because it writes directly to the response body.

Keep domain exceptions meaningful, such as OrderNotFoundException or PaymentDeclinedException. The advice layer can then translate them into transport concerns without coupling business services to HttpServletRequest or ResponseEntity.

Designing a stable error contract

Clients benefit from one response shape, even when several exceptions cause the same HTTP status. Include a timestamp, status, machine-readable code, safe message, request path and optional field errors; clients can then branch on code rather than parse prose.

A small immutable record works well in Java 17 and later:

public record ApiError(
    Instant timestamp,
    int status,
    String code,
    String message,
    String path,
    Map<String, String> fieldErrors
) {}

Document the contract and version it if external consumers depend on it. A stable code such as ORDER_NOT_FOUND is more durable than wording that may be adjusted for clarity or tone.

Implementing the global handler

Create a dedicated handler and register each supported exception explicitly. Spring selects the closest matching @ExceptionHandler method, so specificity matters when exception types overlap.

@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(OrderNotFoundException.class)
    public ResponseEntity<ApiError> handleNotFound(
            OrderNotFoundException ex,
            HttpServletRequest request) {

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
            new ApiError(
                Instant.now(),
                404,
                "ORDER_NOT_FOUND",
                ex.getMessage(),
                request.getRequestURI(),
                Map.of()));
    }
}

Use constructor injection for collaborators and HttpServletRequest for the request path. Log unexpected failures server-side with a correlation identifier, but return only a safe client message. Do not include stack traces, SQL fragments or provider payloads in the body.

If the API already standardises on RFC 9457 ProblemDetail, that format can replace the custom record. The same advice mechanism still applies, provided handlers set the correct status and extension fields.

Handling validation and domain failures

Bean Validation failures need field-level context. A handler for MethodArgumentNotValidException can collect each rejected property and return the same ApiError structure with HTTP 400.

Map<String, String> fields = new LinkedHashMap<>();

ex.getBindingResult().getFieldErrors().forEach(error ->
    fields.putIfAbsent(
        error.getField(),
        error.getDefaultMessage()
    )
);

Map authentication failures to 401, forbidden access to 403, missing resources to 404 and state conflicts to 409. A declined payment or unavailable provider may need a separate business code even when both use an appropriate 4xx status.

Avoid a catch-all handler that disguises programming errors as ordinary validation failures. Let genuine defects reach the framework’s error handling, retain their diagnostics in logs and alert the owning team.

Adapting responses for Australian clients

Keep API data in interoperable formats, then let presentation layers apply Australian conventions. Store timestamps as ISO 8601 values, but format dates as dd/MM/yyyy; display Australian dollars as A$ and state clearly whether a consumer price includes GST.

These choices matter in real Australian contexts: a Sydney fintech can call a payment gateway, a Melbourne retailer can offer GST-inclusive checkout, and a Brisbane field-service team can rely on Australian addresses and phone formats. The backend should carry the correct currency code and tax context rather than rely on English labels alone.

Authentication errors should not reveal whether an account exists. Generic responses reduce account-enumeration risk and align with guidance from the Australian Cyber Security Centre and privacy obligations under the Privacy Act 1988. Apply the same caution to order numbers, customer records and payment details.

Production patterns and verification

Keep the handler small, deterministic and safe to expose publicly. Useful safeguards include:

Then verify the outcomes that affect API consumers and operations:

Monitor error rates by code and status, and treat any newly introduced code as part of the public contract. This gives Sydney, Melbourne and Brisbane teams a dependable integration surface while preserving the detail developers need during diagnosis.