@ControllerAdvice와 @ExceptionHandler
예외를 전역에서 처리해 보세요.
@ControllerAdvice와 @ExceptionHandler은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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
자주 묻는 질문
“@ControllerAdvice와 @ExceptionHandler” 강의는 무료인가요?
네 — “@ControllerAdvice와 @ExceptionHandler” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“@ControllerAdvice와 @ExceptionHandler”에서 뭘 배우나요?
예외를 전역에서 처리해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“@ControllerAdvice와 @ExceptionHandler” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- @Valid로 빈 검증하기
- 사용자 지정 검증기
- @ControllerAdvice와 @ExceptionHandler
- 문제 세부 정보(RFC 7807)