Course outline

Spring Boot / Basic: composition and HTTP contracts / Lesson 7

Controller advice and safe errors

Map expected application exceptions to consistent HTTP errors while keeping internal details private.

About 3 min readContent reviewed
On this page

Lesson goals

  • Explain the role of controller advice in MVC.
  • Map a defined exception to an intentional status and body.
  • Test error handling and unchanged state on failure.

Separate errors by boundary

An HTTP request can fail during binding, validation, authorization or an application operation. Each has a distinct cause and may need a different response. Controller advice can centralize selected MVC exception mappings, but it does not replace security filters or database transaction handling. Define a stable public error contract without exposing stack traces, database details, credentials or private input.

Define an application exception

The first fragment defines a specific missing-resource exception. A service can raise it when an authorized lookup finds no resource, according to the applicationโ€™s disclosure policy. Do not use one broad exception for every failure: an unavailable database is different from a missing record. Preserve the original exception for safe server-side diagnostics where appropriate, but do not return internal messages directly to clients.

java Define a specific missing-resource exception
public class ResourceMissingException extends RuntimeException {
    public ResourceMissingException() { super("Resource not found"); }
}

The application decides when this exception is appropriate and whether the resource may be disclosed.

Map a safe response

The advice fragment maps the defined exception to a simple 404 body. It assumes the application registers the advice and uses the exception consistently. Other exceptions need their own intentional mappings; the example does not claim to handle security-filter failures. If using problem details, document stable fields and content type for the deployed framework version. Keep any correlation identifier safe and avoid putting sensitive resource data in the response.

java Map the exception with controller advice
@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(ResourceMissingException.class)
    ResponseEntity<Map<String, String>> missing() {
        return ResponseEntity.status(404).body(Map.of("error", "Resource not found"));
    }
}

The advice handles the defined exception in MVC. Other failures and security filters require their own configured handling.

Preserve state on failure

A response mapping changes what the client sees; it does not itself undo partial writes. Define transaction boundaries and rollback behavior in the service layer, then test them with a disposable database. Reject malformed or unauthorized requests before performing effects where possible. If an external effect has already happened, a database rollback cannot reverse it; use an explicit recovery or idempotency strategy.

Test both error and control

Use an MVC test to send a request for a missing synthetic resource and assert status and safe response fields. Add an allowed control request, and separately exercise validation and authentication failures through their actual configured boundaries. For a rejected write, inspect durable state after the response. A web slice that mocks the service demonstrates mapping, not the real repository or transaction behavior.

Common errors and fixes

Every failure becomes a 404

Why it happens
A broad exception handler hides infrastructure and programming errors.
How to fix it
Map only the expected exception and handle other failures appropriately.
Prevent it next time
Test missing-resource and dependency-failure cases separately.

An error response leaks database details

Why it happens
The exception message was returned directly.
How to fix it
Return a stable safe message and retain controlled diagnostics server-side.
Prevent it next time
Test response fields with synthetic sensitive values.

A 400 response leaves a partial write

Why it happens
Response handling was mistaken for transaction rollback.
How to fix it
Define the transaction and rollback rules around the write.
Prevent it next time
Force a failure between writes and inspect durable state.

2 practice exercises

1. A lookup fails because the database is unavailable. Should the missing-resource advice return 404?

Show worked solution

No. Distinguish infrastructure failure from an authorized lookup that found no record. Map the failure according to the application contract and keep internal connection details out of the response.

2. How do you verify that a failed update did not persist half its changes?

Show worked solution

Use a disposable database, trigger failure between the changes and inspect the stored state from a fresh transaction. Assert the HTTP response separately; advice alone does not provide rollback.

Key takeaways

  • Map specific expected errors to safe, stable HTTP responses.
  • Response mapping and transaction recovery are separate responsibilities.

Official references