Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 21

    Exception Handling

    Orders should fail with a stable JSON error shape, not a stack trace HTML page.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Orders should fail with a stable JSON error shape, not a stack trace HTML page. On Boot 3, @ControllerAdvice plus ProblemDetail (RFC 9457) is the modern default path.

    Throw domain exceptions from the service (OrderNotFoundException, OrderConflictException). Advice maps them to status codes and problem details. Controllers stay free of try/catch noise.

    Validation failures from @Valid become MethodArgumentNotValidException — handle them once in advice.

    Never return raw exception messages that leak SQL or file paths to clients.

    Purpose of this lesson

    Centralize Orders error translation with @ControllerAdvice and ProblemDetail-style responses.

    Understanding the topic

    Exceptions are part of the API if clients can see them.

    • Domain exceptions: express business failures.
    • @ExceptionHandler: per-advice methods for types you care about.
    • ProblemDetail: type, title, status, detail, instance — keep detail safe.
    • Fallback: generic 500 handler that logs fully and returns a opaque id.
    • No stack traces in production responses.

    Step-by-step explanation

    1. Create OrderNotFoundException.
    2. Throw it from OrderService.get.
    3. Add @RestControllerAdvice mapping it to 404 ProblemDetail.
    4. Confirm server.error.include-stacktrace=never in config.

    Informative example

    Not-found advice.

    java
    @RestControllerAdvice
    public class OrdersExceptionHandler {
    @ExceptionHandler(OrderNotFoundException.class)
    ProblemDetail notFound(OrderNotFoundException ex) {
    ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
    pd.setTitle("Order not found");
    pd.setDetail("No order exists for the given id.");
    return pd;
    }
    }

    Real-world use

    Support engineers correlate client error bodies with server logs via a correlation id. TechLearningPRO Orders should log the stack once server-side and return a short, safe detail to the app.

    Security implications

    Error bodies are an information channel.

    • Pin stacktrace inclusion to never in prod.
    • Do not reveal whether an email exists via differing error messages if that matters.
    • Log thoroughly; respond minimally.

    Best practices

    • One advice class (or a small set) for HTTP APIs.
    • Map domain exceptions explicitly; do not overuse generic handlers.
    • Include a correlation id header/body field when you have tracing.

    Common mistakes

    • Catching Exception in every controller method.
    • Returning ex.getMessage() from JDBC exceptions.
    • Inconsistent error JSON per endpoint.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is @ControllerAdvice for?+

    Answer

    Centralized cross-cutting handling — especially exception-to-HTTP translation — across controllers.
    2IntermediateQuestionWhat is ProblemDetail in Boot 3?+

    Answer

    A standard error payload (RFC 9457) with status, title, detail, and optional type/instance fields.
    3IntermediateQuestionWhy not expose SQLException messages?+

    Answer

    They leak schema and infrastructure details useful to attackers and useless to most clients.

    Hands-on exercise

    Lab. Throw OrderNotFoundException and return ProblemDetail 404. Force a generic exception and ensure the client does not receive a stack trace.

    Summary

    Stable Orders errors come from advice, not ad-hoc catches. Next you validate inputs before the service runs.

    Ready to mark this lesson complete?Track your journey across the entire course.