Error Handling: Failing Gracefully

Error Handling: Failing Gracefully in Java: When something goes wrong, an API has two choices: leak a Java stack trace, or return a clean, documented error.

Concept Explanation

When something goes wrong, an API has two choices: leak a Java stack trace, or return a clean, documented error. The first is a security problem and a bad developer experience. The second takes about twenty lines to set up once.

The tool is @RestControllerAdvice — a class that intercepts exceptions from every controller.


Meaningful Exceptions

Start by throwing something specific instead of returning null:

public class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(Long id) {
        super("No product with id " + id);
    }
}
public Product byId(Long id) {
    return repo.findById(id)
               .orElseThrow(() -> new ProductNotFoundException(id));
}

One Handler For The Whole App

@RestControllerAdvice
public class ApiExceptionHandler {

    private static final Logger log =
        LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(ProductNotFoundException.class)
    public ResponseEntity<ApiError> notFound(ProductNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                             .body(new ApiError("NOT_FOUND", ex.getMessage()));
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiError> badRequest(IllegalArgumentException ex) {
        return ResponseEntity.badRequest()
                             .body(new ApiError("BAD_REQUEST", ex.getMessage()));
    }

    @ExceptionHandler(Exception.class)                 // the safety net
    public ResponseEntity<ApiError> unexpected(Exception ex) {
        log.error("Unhandled exception", ex);          // full detail in the log
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                             .body(new ApiError("INTERNAL", "Something went wrong"));
    }
}

Note the split in the last handler: the log gets the stack trace, the client gets a generic message. That is the rule for every 500.


A Consistent Error Shape

public record ApiError(String code, String message) { }

Every failure now looks the same, so clients can write one error-handling path instead of five.


Status Code Cheat Sheet

SituationStatus
Validation failed400 Bad Request
Not logged in401 Unauthorized
Logged in, not allowed403 Forbidden
Resource missing404 Not Found
Duplicate / conflicting state409 Conflict
Bug on your side500 Internal Server Error

Common Mistakes

  1. Returning 200 with an error body: Clients and monitoring both rely on the status code. Never lie about success.
  2. Leaking stack traces: They reveal your framework versions, package layout, and sometimes SQL. Log them; do not send them.
  3. catch (Exception e) {}: Swallowing an exception makes the failure invisible and the bug unfindable.
  4. 404 for permission failures: Use 403. A 404 sends the client hunting for a typo that does not exist.

Best Practices

  • One error shape for the whole API, documented alongside the endpoints.
  • Always keep a catch-all handler so no exception can escape as raw HTML.
  • Log with context: Include the request path and, if you have one, a correlation id.

Practice Exercises

  1. The Clean 404: Throw a custom not-found exception and confirm the response is your ApiError shape, not Spring's default page.
  2. The Safety Net: Deliberately divide by zero in a controller. Verify the client sees a generic message while the log holds the full trace.
  3. The Conflict: Return 409 when creating a product whose name already exists.