Video in progress
Where should exceptions be logged? In a global `@RestControllerAdvice`, at what level and how do you log 4xx and 5xx errors?
Log an exception once, at the place that finally handles it, usually the global handler. 4xx is a client error: WARN or INFO, without a stack trace. 5xx is our error: ERROR with the full stack trace. The lower layers only add context and wrap the exception.
📖 Answer
The typical picture: the repository logs the error and rethrows it, the service logs it again and rethrows, and the controller does the same. The result is one error three times in the log, each with a full stack trace. You get three times as many alerts, and during an incident it is hard to find which line is the original.
My rule: a lower layer either handles the error itself (and logs a WARN if needed), or wraps it with context and rethrows without logging. The global handler writes the log:
@RestControllerAdvice
class ApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
log.info("Buyurtma topilmadi: {}", e.getMessage()); // no stack trace needed
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(Exception.class)
ProblemDetail unexpected(Exception e) {
log.error("Kutilmagan xato", e); // full stack trace
return ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Why 4xx is not ERROR: a wrong password or a missing ID means the system is working correctly. If those were ERROR, your error alerts would fire because of client mistakes. A sharp rise in the share of 4xx is still a signal (for example, a new version of the mobile app sends malformed requests), but it is better to watch it in the http_server_requests{status=~"4.."} metric than in the logs.
Don't return the internal error text in the response: give the client a generic message and a traceId, and keep the details in the log. In Spring Boot 3, ProblemDetail makes this clean.
Sign up to mark studied questions and save your progress.