Exception Handling in Spring Boot
Spring MVC does not turn every Java exception into a useful API response automatically. An exception travels from the controller through the dispatcher servlet. If no application handler claims it, Spring returns a generic error response, commonly HTTP 500. The goal is to choose one boundary where technical failures become a stable HTTP contract.

From method failure to HTTP response
A request first enters the servlet filter chain, then DispatcherServlet selects a controller method. The controller calls a service, and the service may throw a domain exception. If the controller does not catch it, the exception propagates back through Spring MVC. Catching it in every controller is possible but creates duplication and inconsistent JSON.
@RestController
@RequestMapping("/users")
class UserController {
private final UserService service;
@GetMapping("/{id}")
UserResponse find(@PathVariable long id) {
return UserResponse.from(service.findUser(id));
}
}
Returning null from findUser is not error handling. It forces the controller or serializer to guess what absence means and may create a later NullPointerException. A service should express a missing user with UserNotFoundException; a web boundary should map that exception to 404.
| Layer | Responsibility | Example failure |
|---|---|---|
| controller | Parse request and call the use case | malformed path variable |
| service | Enforce business rules | user does not exist |
| repository | Access persistence | database unavailable |
| exception boundary | Map failure to public contract | exception to HTTP status and JSON |
Error response DTO
Do not expose an exception object or stack trace directly to a client. Define a small response model with stable fields:
public record ErrorResponse(
String code,
String message,
String path
) {}
The code is useful for clients and support; the message is safe human context; the path identifies the request. A production response may also contain a request ID. Internal logs should contain the exception and cause, while the client receives only the fields promised by the API.
Glossary
- bytecode
- Platform-independent compiled code that the JVM can execute.
- class
- A blueprint that defines fields and methods for objects in object-oriented programming.
- object
- A runtime instance of a class with its own state and behavior.
- method
- A named block of behavior that belongs to a class or object and can be called by code.
- field
- A variable stored inside a class or object that represents part of its state.
- constructor
- A special method-like block used to create and initialize a new object.
- package
- A namespace that groups related Java classes and helps organize code.
- interface
- A contract that defines methods a class can implement without prescribing all internal details.
- generics
- A language feature that lets code work with types as parameters while preserving type safety.
- type erasure
- The Java compiler process that removes most generic type details from runtime bytecode.
- collection
- A data structure that stores a group of elements and provides operations over them.
- list
- An ordered collection where elements have positions and duplicates are allowed.
- set
- A collection that stores unique elements and is commonly used for membership checks.
- map
- A key-value data structure where each key points to a value.
- queue
- A collection designed for processing elements in a defined order, often first-in-first-out.
- lambda
- A compact function-like expression used to pass behavior as data.
- functional interface
- An interface with one abstract method, suitable for lambdas and method references.
- stream
- A Java API for processing data sequences with operations such as map, filter, and reduce.
- optional
- A container object that represents a value that may or may not be present.
- thread
- An independent path of execution inside a running program.
- synchronization
- Coordination that protects shared data when multiple threads access it.
- heap
- The runtime memory area where Java objects are allocated.
- stack
- The runtime memory area that stores method calls, local variables, and call frames.
- garbage collector
- A JVM component that automatically frees memory occupied by objects no longer reachable.
- memory leak
- A situation where memory remains occupied because objects are still referenced but no longer useful.