Video in progress
Which of the following catch blocks logs the error correctly, and why?
try {
paymentClient.charge(order);
} catch (PaymentException e) {
log.error("To'lov xatosi: " + e.getMessage()); // 1
log.error("To'lov xatosi: {}", e.toString()); // 2
log.error("To'lov xatosi: orderId={}", order.getId(), e); // 3
}
Only the third: when you pass the exception as the last argument, SLF4J prints the whole stack trace. The first writes only the message, and the second writes toString(), so where the error came from is lost.
📖 Answer
Option 1: only getMessage() is written. Often it is null or something generic like "Connection reset". You can't tell which line it came from or which cause produced it.
Option 2: toString() gives just the class name and the message. The exception is now a plain string, SLF4J doesn't recognize it as a Throwable, and no stack trace is printed.
Option 3 is correct: the business context (orderId) goes into the placeholder, and the exception goes separately as the last argument. The log has both the message and the Caused by: chain.
Two more common mistakes:
e.printStackTrace(): it goes to stderr and stays outside the log format;- logging one exception at every layer and then throwing it again: one error shows up in the log 4 times. Either log it or throw it, not both.
Sign up to mark studied questions and save your progress.