Exception Handling

Basic Spring
≈ 1 min read

A Java error should become a clear HTTP response

A service can report an error with an exception: for example, the requested resource may not exist. If nothing is configured, the internal exception and the external HTTP contract become too tightly coupled. Spring MVC lets you describe separately how a particular error should look to the client.

@RestControllerAdvice
class ApiExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    ResponseEntity<ApiError> handle(UserNotFoundException ex) {
        return ResponseEntity.status(404)
                .body(new ApiError(ex.getMessage()));
    }
}

@ExceptionHandler connects an exception type to a handling method. @RestControllerAdvice lets you move such methods out of individual controllers and apply them to the web layer centrally.

Why a centralized handler is useful

Without a shared layer, every controller starts repeating the same try/catch blocks and formatting errors in its own way. Advice makes it possible to keep one error format and consistent rules for mapping common exceptions to HTTP statuses.

Do not send internal exception details to the client unless necessary. Stack traces, SQL text, and service messages are useful in logs, but an external API should usually return a stable and safe error structure.