@ControllerAdvice y @ExceptionHandler
Gestione excepciones de forma global
@ControllerAdvice y @ExceptionHandler es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Problem with Scattered Try/Catch
Handling errors with try/catch in every controller duplicates code and produces inconsistent responses. Spring MVC offers a centralized model: exception handlers that turn exceptions into clean HTTP responses.
Local @ExceptionHandler
A method annotated @ExceptionHandler inside a controller handles the listed exception types for that controller. It maps an exception to a response.
@RestController
public class OrderController {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<String> handleNotFound(OrderNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}Going Global with @ControllerAdvice
@ControllerAdvice (or @RestControllerAdvice) hosts exception handlers that apply across all controllers. This centralizes error handling in one class.
@RestControllerAdvice
public class GlobalExceptionHandler {
// handlers shared by every controller
}Handling a Domain Exception
Define handlers for your own exceptions, returning the right status and a structured body. The same logic now serves every endpoint.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError notFound(ResourceNotFoundException ex) {
return new ApiError("NOT_FOUND", ex.getMessage());
}
}A Consistent Error DTO
Return a uniform error shape so clients can parse failures predictably. Include a code, a human message, and optionally a timestamp and field details.
public record ApiError(
String code,
String message,
Instant timestamp) {
public ApiError(String code, String message) {
this(code, message, Instant.now());
}
}Handling Validation Errors
Catch MethodArgumentNotValidException to convert Bean Validation failures into a clear, field-by-field response instead of Spring’s default body.
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
return errors;
}A Catch-All Handler
Add a handler for Exception as a safety net, returning 500 with a generic message. Crucially, log the real exception but never leak stack traces to clients.
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiError handleUnexpected(Exception ex) {
log.error("Unhandled error", ex);
return new ApiError("INTERNAL_ERROR", "Something went wrong");
}Handler Selection Order
Spring picks the handler whose exception type most closely matches the thrown exception. A handler for OrderNotFoundException beats one for its superclass, so specific handlers take priority.
Scoping the Advice
You can narrow a @ControllerAdvice to specific packages, annotations, or controller types, allowing different error policies for, say, public vs internal APIs.
@RestControllerAdvice(basePackages = "com.example.api.publicapi")
public class PublicApiExceptionHandler { }Accessing the Request
Handler methods can accept extra parameters like WebRequest or HttpServletRequest to enrich responses with the path or a correlation id.
@ExceptionHandler(ResourceNotFoundException.class)
public ApiError notFound(ResourceNotFoundException ex, HttpServletRequest req) {
return new ApiError("NOT_FOUND", ex.getMessage() + " at " + req.getRequestURI());
}Security: Do Not Over-Share
Error responses are a common information-leak vector. Return enough for clients to act, but never expose internal class names, SQL, or stack traces. Log details server-side instead.
Quick Check
Test your understanding of centralized handling.
Recap
Centralize error handling.
@ExceptionHandlermaps exceptions to responses@ControllerAdviceapplies handlers across all controllers- Return a consistent error DTO
- Handle validation, domain, and catch-all cases
- Most specific handler wins; never leak internals to clients
Preguntas frecuentes
¿La lección «@ControllerAdvice y @ExceptionHandler» es gratis?
Sí — el texto completo de «@ControllerAdvice y @ExceptionHandler» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «@ControllerAdvice y @ExceptionHandler»?
Gestione excepciones de forma global Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «@ControllerAdvice y @ExceptionHandler»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Validación de beans con @Valid
- Validadores personalizados
- @ControllerAdvice y @ExceptionHandler
- Detalles del problema (RFC 7807)