Skip to content
notes.vinhnq.com

Search

Java CoreMid22 min read

Custom exceptions and centralized error handling in Spring Boot: @RestControllerAdvice, ProblemDetail, validation

Review 17 cards
On this page

Exceptions and error handling series: 1. Exceptions in Java · 2. Custom exceptions and error handling in Spring Boot

Part 1 covered exceptions in core Java. In a real application the question becomes: which exception describes this business error, where do you catch it, and what do you send back to the client. After this post you can design custom exceptions with error codes, centralize handling in @RestControllerAdvice, return ProblemDetail, and validate DTOs with Bean Validation.

1. Custom exceptions

Key idea: separate business errors (thrown on purpose by your code) from system errors, using one unchecked base exception that carries an error code from an enum.

  • System exceptions: thrown by the platform, frameworks or libraries (DB timeouts, NPEs, I/O failures).
  • Business/custom exceptions: thrown deliberately by your logic (email already registered, insufficient balance, order already cancelled).

The error code must be stable: clients branch on it, while messages may change or get translated.

public enum ErrorCode {
    USER_EMAIL_TAKEN(HttpStatus.CONFLICT, "The email is already registered"),
    USERNAME_TAKEN(HttpStatus.CONFLICT, "The username is already taken"),
    USER_NOT_FOUND(HttpStatus.NOT_FOUND, "User not found"),
    ORDER_ALREADY_PAID(HttpStatus.CONFLICT, "Order has already been paid"),
    VALIDATION_FAILED(HttpStatus.BAD_REQUEST, "Request is invalid"),
    INTERNAL(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");

    private final HttpStatus status;
    private final String defaultMessage;

    ErrorCode(HttpStatus status, String defaultMessage) {
        this.status = status;
        this.defaultMessage = defaultMessage;
    }
    public HttpStatus status() { return status; }
    public String defaultMessage() { return defaultMessage; }
}

public class BusinessException extends RuntimeException {
    private final ErrorCode code;

    public BusinessException(ErrorCode code) {
        super(code.defaultMessage());     // pass the message up to Throwable
        this.code = code;
    }
    public BusinessException(ErrorCode code, String detail) {
        super(detail);
        this.code = code;
    }
    public ErrorCode code() { return code; }
}

The code-design side of this question (why checked exceptions break Open-Closed, wrapping library exceptions at the boundary with their cause) is in Clean code: error handling, boundaries and refactoring.

Two details when writing your own exceptions: cause and serialVersionUID
  • Add a constructor that takes a Throwable cause (super(message, cause)). When you wrap an infrastructure failure (SQLException, IOException), the cause keeps the original stack trace. Without it the log tells you where it was thrown but not why.
  • IDEs often warn about a missing serialVersionUID, because Throwable implements Serializable. Modern applications almost never send exceptions through Java serialization (API errors go out as JSON). Declaring private static final long serialVersionUID = 1L; or turning the warning off is all you need.

Gotcha: @Transactional and checked exceptions

A rollback can only undo what lives in the database. A “save then publish” method (repo.save(order); kafkaTemplate.send(...)) can still drift: if the commit succeeds and the publish fails, other services never learn the order exists; if the publish goes out and the transaction rolls back, they learn about an order that doesn’t exist. The fix with a transactional outbox is in the “dual write” pitfall of Message brokers and how to choose one.

2. Exceptions in Spring Boot

Key idea: controllers and services just throw; one @RestControllerAdvice class catches everything and returns the same ProblemDetail format, logged at the right level.

The path a request takes through DispatcherServlet, where exceptions from handlers are passed to @ControllerAdvice, is in Spring MVC: DispatcherServlet, controllers and views.

The problem with try-catch everywhere

@PostMapping("/users")
public ResponseEntity<?> create(@RequestBody CreateUserRequest req) {
    try {
        return ResponseEntity.ok(userService.create(req));
    } catch (BusinessException e) {
        return ResponseEntity.status(409).body(e.getMessage());
    } catch (Exception e) {
        log.error("create user failed", e);
        return ResponseEntity.status(500).body("error");
    }
}

Multiply that by 50 endpoints: duplicated code, everyone invents their own error format, logging gets forgotten, details leak.

@ControllerAdvice and @ExceptionHandler

  • @ExceptionHandler(X.class): a method that handles exceptions of type X (and its subclasses).
  • @ControllerAdvice: a class whose handlers apply to all controllers. @RestControllerAdvice = @ControllerAdvice + @ResponseBody.
flowchart LR
  C[Client] --> DS[DispatcherServlet]
  DS --> Ctrl[Controller]
  Ctrl --> Svc[Service]
  Svc -- throw BusinessException --> Ctrl
  Ctrl -- exception escapes --> DS
  DS --> HER[ExceptionHandlerExceptionResolver]
  HER --> Adv["@RestControllerAdvice<br/>picks the closest @ExceptionHandler"]
  Adv -- ProblemDetail JSON --> C

How a handler is chosen:

  1. Handlers in the controller itself win over advice handlers.
  2. With several advice classes, @Order decides.
  3. Within a class, the handler whose type is the closest match in the inheritance tree wins (declaration order doesn’t matter).

ProblemDetail (RFC 9457)

Since Spring 6 / Boot 3, Spring supports ProblemDetail out of the box: the standard error format from RFC 9457 (which supersedes RFC 7807), served as application/problem+json.

{
  "type": "https://api.example.com/errors/user-email-taken",
  "title": "Conflict",
  "status": 409,
  "detail": "The email is already registered",
  "instance": "/api/users",
  "code": "USER_EMAIL_TAKEN",
  "traceId": "6f1c2a9e8b7d4c10"
}

Standard members: type, title, status, detail, instance. Extension members like code, traceId and errors are allowed.

Set spring.mvc.problemdetails.enabled=true so Spring MVC’s built-in exceptions (wrong method, missing parameter, malformed JSON body…) render as ProblemDetail automatically. Or extend ResponseEntityExceptionHandler yourself, like the handler below with three layers: business errors, validation errors, safety net.

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    // 1. Business errors: "expected" failures, log at WARN/INFO, no stack trace needed
    @ExceptionHandler(BusinessException.class)
    ProblemDetail handleBusiness(BusinessException ex, HttpServletRequest req) {
        ErrorCode code = ex.code();
        log.info("Business error {} on {}: {}", code, req.getRequestURI(), ex.getMessage());
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(code.status(), ex.getMessage());
        pd.setType(URI.create("https://api.example.com/errors/" + code.name().toLowerCase().replace('_', '-')));
        pd.setProperty("code", code.name());
        return pd;
    }

    // 2. @RequestBody validation errors: override the hook ResponseEntityExceptionHandler provides
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request is invalid");
        pd.setProperty("code", ErrorCode.VALIDATION_FAILED.name());
        pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
                .map(fe -> Map.of("field", fe.getField(),
                                  "message", Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid")))
                .toList());
        return ResponseEntity.badRequest().body(pd);
    }

    // 3. Last safety net: log at ERROR with the stack trace, DON'T send details to the client
    @ExceptionHandler(Exception.class)
    ProblemDetail handleUnknown(Exception ex, HttpServletRequest req) {
        log.error("Unhandled error on {} {}", req.getMethod(), req.getRequestURI(), ex);
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(
                HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong, please try again later");
        pd.setProperty("code", ErrorCode.INTERNAL.name());
        return pd;
    }
}

This net catches Exception, not Error: an OutOfMemoryError still flies past it. When a pod is OOMKilled, the kernel kills the process with SIGKILL, so no handler and no log line gets to run. How the two differ and how to size a JVM container’s memory limit is in Virtual memory, page cache and the JVM in containers.

Designing the error response

  • No internal details for the client: no stack traces, SQL, class names, or raw messages from system exceptions. That’s free reconnaissance for an attacker (library versions, table structure). Details go to logs; the client gets a safe message plus a traceId to correlate.
  • A stable error code (code) so web and mobile clients branch on logic, not on message strings.
  • One format for the whole system, including filter and Spring Security errors. Anything failing before DispatcherServlet never reaches @ControllerAdvice; handle it with an AuthenticationEntryPoint, AccessDeniedHandler or the /error page.
  • Log at the right level: 4xx are usually the client’s fault, WARN/INFO is enough; 5xx get ERROR with a stack trace and should trigger alerts.
  • Spring Boot defaults to server.error.include-stacktrace=never and include-message=never. Don’t turn them on in production.

Semantically correct HTTP status:

Status When
400 bad input
401 / 403 not authenticated / not allowed
404 resource not found
409 state conflict
422 syntactically valid but violates business rules (team convention)
429 rate limited
500 / 503 server error / a dependency is down

Leaking error details falls under A05 Security Misconfiguration in the OWASP Top 10; how the other items map to Spring Security is in Web attacks and the OWASP Top 10.

The traceId in the response must match logs and tracing

A traceId only helps if it matches the id in your logs and your tracing system. With the OpenTelemetry Java agent, trace_id is already in the MDC (the key-value map attached to the logging thread), so the handler just reads it or takes it from Span.current() instead of generating its own UUID.

How the trace id travels between services in the traceparent header, and how to print it in logs, is covered in Distributed tracing with OpenTelemetry.

3. DTO validation

Key idea: validate at several levels: format on the DTO with Bean Validation, business rules in the service, and database constraints as the last guard. Let validation errors escape to the global handler instead of handling them in each controller.

The Thymeleaf form version (BindingResult, errors shown in the view) is in form binding and validation in Spring MVC; record DTOs, custom constraints and normalizing before the uniqueness check are in DTOs, responses and validation for a REST API.

Three levels of validation:

  • Boundary (DTO): format checks with annotations.
  • Service: business rules (is the username taken?).
  • Database: NOT NULL, UNIQUE, FK, CHECK as the last line of defense.

The layers of a Spring Boot project

Responsibilities per layer: Controller, DTO, Service, Repository, Entity
Layer Responsibility
Controller Receives requests, maps endpoints, converts DTOs, calls services
DTO Carries data between layers and over the API, keeps sensitive entity fields from leaking
Service Business logic, transactions, calls repositories
Repository Queries and modifies data
Entity Maps to database tables

Bean Validation with spring-boot-starter-validation

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

This starter brings in Hibernate Validator (the implementation of Jakarta Bean Validation, the standard set of annotations for declaring validity rules). Since Spring Boot 2.3 it is no longer included in spring-boot-starter-web, so add it explicitly.

The ones you’ll use most: @NotNull, @NotBlank, @Size, @Min/@Max, @Email, @Pattern, @Past, and @Valid to cascade into nested objects.

Full table of Bean Validation annotations
Annotation Checks
@NotNull not null
@NotEmpty not null and not empty (String, Collection, Map, array)
@NotBlank String not null and containing at least one non-whitespace character
@Null must be null (e.g. id on create)
@Size(min, max) length of a String/Collection/Map/array
@Min, @Max integer bounds
@Positive, @PositiveOrZero, @Negative, @NegativeOrZero sign of a number
@Digits(integer, fraction) number of integer/fraction digits
@Pattern(regexp) matches a regex
@Email email format
@Past, @PastOrPresent, @Future, @FutureOrPresent date/time relative to now
@AssertTrue, @AssertFalse boolean value
@Valid cascade validation into nested objects

@Pattern runs java.util.regex on user input, and Java regexes have no timeout: an ambiguous pattern is a ReDoS hole (a regex that runs for ages on crafted input). An @Size next to it doesn’t help, because Bean Validation doesn’t guarantee constraint order. How to write safe patterns is in ReDoS in Java.

public record CreateUserRequest(
        @NotBlank @Size(max = 50) String username,
        @NotBlank @Size(min = 10, max = 72) String password,   // bcrypt only uses the first 72 bytes
        @NotBlank @Email String email,
        @NotNull @Past LocalDate birthDate,
        @Valid @NotNull AddressDto address,
        @Size(max = 5) List<@NotBlank String> tags                // validate each element
) {}

Two ways to handle validation failures

Option 1: a BindingResult parameter right after the validated parameter. When it’s present, Spring does not throw; the controller deals with the errors itself.

@PostMapping("/users")
public ResponseEntity<?> create(@Valid @RequestBody CreateUserRequest req, BindingResult result) {
    if (result.hasErrors()) {
        Map<String, String> errors = result.getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField,
                        fe -> Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid"),
                        (first, second) -> first));
        return ResponseEntity.badRequest().body(errors);
    }
    return ResponseEntity.status(HttpStatus.CREATED).body(userService.create(req));
}

Option 2: let the exception escape to the global handler (override handleMethodArgumentNotValid as in section 2).

Validating @PathVariable and @RequestParam

Put the constraints directly on the parameters:

@GetMapping("/users/{id}")
public UserResponse get(@PathVariable @Positive long id,
                        @RequestParam(defaultValue = "20") @Max(100) int size) { ... }

How this works depends on the version, so “same as DTOs”, as the material puts it, isn’t the whole story:

Version Requirement Exception on failure Default response
Spring 6.0 and earlier @Validated on the controller class (method validation through an AOP proxy) ConstraintViolationException 500 unless you handle it
Spring 6.1+ (Boot 3.2+) Built-in method validation, no @Validated needed HandlerMethodValidationException 400

On the older setup, remember to add a handler that maps ConstraintViolationException to 400.

Manual validation

Only write validation by hand when the library can’t do it: you need to call another system, or look something up in the database (username already taken).

@Transactional
public UserResponse create(CreateUserRequest req) {
    if (userRepository.existsByUsername(req.username())) {
        throw new BusinessException(ErrorCode.USERNAME_TAKEN);
    }
    try {
        return UserResponse.from(userRepository.saveAndFlush(User.from(req)));
    } catch (DataIntegrityViolationException e) {
        // Two concurrent requests can both pass the exists check: the UNIQUE constraint is the real guard
        throw new BusinessException(ErrorCode.USERNAME_TAKEN);
    }
}

Two things a senior engineer should spot:

  • @Valid on a parameter of a service method does nothing by itself. The service class needs @Validated so Spring wraps it in a proxy that performs method validation (throwing ConstraintViolationException). Since it’s a proxy, internal calls (this.create(...)) bypass validation.

You can also write your own constraints (an annotation meta-annotated with @Constraint plus a ConstraintValidator implementation) for reusable rules like @StrongPassword or @VietnamPhone, or class-level rules such as “endDate must be after startDate”.

Exercises

Exercise 1: A bank account with checked and unchecked custom exceptions

The task (paraphrased, Lab 08 from the Hỏi Dân IT material): write a program that opens a bank account and then withdraws money. You need two custom exceptions:

  • a checked one for withdrawing more than the balance;
  • an unchecked one for a password shorter than 6 characters.

A BankAccount class holds a username, a password and a balance; its constructor checks the password, and withdraw(amount) checks the balance, subtracts the amount and prints what’s left. main reads the username, password, starting balance and amount, catches both exceptions, and always prints “Transaction finished.” at the end.

The task calls the checked exception NegativeBalanceException; I renamed it InsufficientBalanceException, because the balance never goes negative: what’s missing is money. An exception’s name should say what actually happened.

Solution to Exercise 1: code, output and what a senior would improve
import java.util.Scanner;

public class BankApp {

    // Checked: callers must handle it, because overdrawing is an expected business case
    static class InsufficientBalanceException extends Exception {
        private final double balance;
        private final double requested;

        InsufficientBalanceException(double balance, double requested) {
            super("Not enough balance to withdraw: balance " + balance + ", requested " + requested);
            this.balance = balance;
            this.requested = requested;
        }

        double shortfall() { return requested - balance; }
    }

    // Unchecked: bad input, so it extends IllegalArgumentException
    static class WeakPasswordException extends IllegalArgumentException {
        WeakPasswordException(int minLength) {
            super("Password must be at least " + minLength + " characters long.");
        }
    }

    static class BankAccount {
        static final int MIN_PASSWORD_LENGTH = 6;

        private final String username;
        private final String password;   // demo only; a real app stores a hash
        private double balance;

        BankAccount(String username, String password, double balance) {
            if (password == null || password.length() < MIN_PASSWORD_LENGTH) {
                throw new WeakPasswordException(MIN_PASSWORD_LENGTH);
            }
            if (balance < 0) {
                throw new IllegalArgumentException("Initial balance must not be negative: " + balance);
            }
            this.username = username;
            this.password = password;
            this.balance = balance;
        }

        void withdraw(double amount) throws InsufficientBalanceException {
            if (amount <= 0) {
                throw new IllegalArgumentException("Withdrawal amount must be positive: " + amount);
            }
            if (amount > balance) {
                throw new InsufficientBalanceException(balance, amount);
            }
            balance -= amount;
            System.out.println("Withdrawal successful. Remaining balance: " + balance);
        }

        double balance() { return balance; }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try {
            System.out.print("Username: ");
            String username = in.nextLine().trim();
            System.out.print("Password: ");
            String password = in.nextLine();
            System.out.print("Initial balance: ");
            double balance = Double.parseDouble(in.nextLine().trim());
            System.out.print("Amount to withdraw: ");
            double amount = Double.parseDouble(in.nextLine().trim());

            BankAccount account = new BankAccount(username, password, balance);
            account.withdraw(amount);
        } catch (WeakPasswordException e) {
            System.out.println("WeakPasswordException: " + e.getMessage());
        } catch (InsufficientBalanceException e) {
            System.out.println("InsufficientBalanceException: " + e.getMessage()
                    + " (short by " + e.shortfall() + ")");
        } catch (NumberFormatException e) {
            System.out.println("Invalid number: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid input: " + e.getMessage());
        } finally {
            System.out.println("Transaction finished.");
        }
    }
}

The three cases from the task, run on JDK 21 (java BankApp.java):

Username: hoidanit
Password: 123456
Initial balance: 5000
Amount to withdraw: 3000
Withdrawal successful. Remaining balance: 2000.0
Transaction finished.

Username: hoidanit
Password: 123
Initial balance: 5000
Amount to withdraw: 3000
WeakPasswordException: Password must be at least 6 characters long.
Transaction finished.

Username: hoidanit
Password: 123456
Initial balance: 2000
Amount to withdraw: 3000
InsufficientBalanceException: Not enough balance to withdraw: balance 2000.0, requested 3000.0 (short by 1000.0)
Transaction finished.

Two cases the task doesn’t mention: a balance of abc prints Invalid number: For input string: "abc"; withdrawing -5 prints Invalid input: Withdrawal amount must be positive: -5.0. Both still end with “Transaction finished.”.

Notes:

  • InsufficientBalanceException extends Exception is checked: withdraw has to declare throws, and main won’t compile if it forgets to catch it. The exception carries balance and requested, so the caller can compute the shortfall (shortfall()) instead of parsing the message.
  • WeakPasswordException extends IllegalArgumentException: still unchecked (IllegalArgumentException is a RuntimeException) and it means exactly “bad input”; code that already catches IllegalArgumentException handles it too.
  • Catch order: WeakPasswordException and NumberFormatException both extend IllegalArgumentException, so they must come before it, or the compiler complains the exception “has already been caught”.
  • If the constructor throws, no object is created, so a BankAccount with a weak password or a negative balance can never exist. That’s how a class protects its own invariants (things that are always true about the object).
  • finally prints “Transaction finished.” in every case, even when the user types a bad number.

What a senior would improve:

  • Never use double for money: 0.1 + 0.2 gives 0.30000000000000004. Use BigDecimal (compare with compareTo, not equals) or a long in the smallest unit (cents).
  • Don’t keep the password in plain text: store only a hash (BCrypt, Argon2). The length rule belongs to input validation (@Size(min = ...) on the DTO, see section 3), not to the account object.
  • Checked or unchecked: in a Spring application, “insufficient balance” is usually an unchecked BusinessException with an error code (INSUFFICIENT_BALANCE, returned as 409 or 422), handled by the global handler. A checked exception fits this exercise because it makes you see the catch-or-declare rule in action.
  • Concurrency: two withdrawals at the same moment can both pass the balance check (check-then-act) and both subtract. Inside one JVM you need a lock; with several instances, let the database enforce it: UPDATE account SET balance = balance - ? WHERE id = ? AND balance >= ? and check the affected row count (see race conditions).
  • Add a cause constructor to the exceptions, and write unit tests for all three branches (success, weak password, insufficient balance) instead of testing by hand.

Exercise 2: Validation in the pet project

The task (paraphrased): in the pet project, use the spring-boot-starter-validation annotations to validate client input, and demonstrate both ways of handling failures: BindingResult for about 10 APIs and @ExceptionHandler for the rest.

Solution to Exercise 2: a shared helper and tests
  1. Create a record request DTO per endpoint with constraints like CreateUserRequest above; use @Valid for nested objects and list elements.
  2. For the 10 BindingResult APIs, write one shared helper that turns a BindingResult into the same format the global handler uses, so the APIs don’t each return something different.
public final class ValidationErrors {
    private ValidationErrors() {}

    public static ResponseEntity<ProblemDetail> badRequest(BindingResult result) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request is invalid");
        pd.setProperty("code", "VALIDATION_FAILED");
        pd.setProperty("errors", result.getFieldErrors().stream()
                .map(fe -> Map.of("field", fe.getField(),
                                  "message", Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid")))
                .toList());
        return ResponseEntity.badRequest().body(pd);
    }
}
  1. For the rest: just @Valid @RequestBody and let GlobalExceptionHandler.handleMethodArgumentNotValid deal with it. Add constraints to @PathVariable/@RequestParam and the matching handler (HandlerMethodValidationException or ConstraintViolationException, depending on version).
  2. Write a @WebMvcTest for each style: send a body with a missing field and assert a 400 status and errors[*].field.

Once you’ve done both, you’ll see why option 2 wins: lean controllers and one consistent error format.

Remember

  • Explain why business errors should be unchecked and carry a stable error code.
  • Know which exceptions make @Transactional roll back, and how to change the default.
  • Trace an exception’s path from the service to @RestControllerAdvice, and name the errors that never take that path.
  • List the fields of a ProblemDetail and the things you never send to a client.
  • Explain why existsByUsername followed by an insert isn’t enough, and what the real guard is.

Interview questions

Junior

Why use @RestControllerAdvice instead of try-catch in every controller?

To handle errors in one place and return one consistent format across the whole API.

Try-catch in every endpoint duplicates code, everyone returns a slightly different format, logging gets forgotten, and internal messages leak. With @RestControllerAdvice, controllers and services just throw; one class decides which exception maps to which status, what the body looks like and at what level it’s logged.

Mid

A @Transactional method throws a checked exception. Does it roll back?

No. By default it only rolls back on RuntimeException and Error.

Use rollbackFor = Exception.class or switch to unchecked exceptions.

How does @ControllerAdvice work, and which handler wins when several match?

ExceptionHandlerExceptionResolver looks in the controller first, then in advice classes ordered by @Order; within a class, the closest exception type wins.

The exception escapes the controller to DispatcherServlet, and that resolver takes over. “Closest” means in the inheritance hierarchy, not in declaration order.

Why shouldn’t you return stack traces or system exception messages to clients?

They leak internals to attackers and mean nothing to users.

What leaks: libraries, versions, DB structure, paths. Return a safe message, an error code and a traceId; keep the details in the logs.

What’s the difference between @Valid and @Validated?

@Valid is the standard Jakarta annotation that triggers validation and cascades into nested objects; Spring’s @Validated adds validation groups and method validation.

@Validated on a class enables method validation through an AOP proxy: needed for services, and for simple controller parameters before Spring 6.1.

Does an exception thrown in a servlet filter or Spring Security reach @ControllerAdvice?

No. Filters run before the DispatcherServlet, and @ControllerAdvice only handles exceptions from handlers the DispatcherServlet invokes.

  • Authentication and authorization failures: an AuthenticationEntryPoint and an AccessDeniedHandler.
  • Other filter errors: the filter writes the response itself, or it falls through to the /error page (BasicErrorController).
  • Whichever path it takes, return the same ProblemDetail format as the rest of the API.

Senior

When would you choose a checked exception in modern code?

When the caller genuinely can and should recover, and forgetting to handle it is dangerous, e.g. in low-level libraries (I/O).

In Spring applications, business errors are usually unchecked and handled centrally, because checked exceptions clutter every layer, don’t work through lambdas/streams and don’t trigger rollback by default.

How would you design error responses for a system with many services?

One shared format (ProblemDetail, RFC 9457) for every service and every error path, with a stable error code and a traceId.

  • Members: type, title, status, detail, plus code for clients, traceId for distributed log lookup and errors for field-level problems.
  • Correct HTTP statuses. Filter and security errors use the same format.
  • When calling other services, map their errors to your own instead of passing them through verbatim.
What’s wrong with calling existsByUsername and then inserting?

It’s a check-then-act race: two concurrent requests can both pass the check.

You need a UNIQUE constraint in the database and should catch DataIntegrityViolationException to return 409. The upfront check is only for failing early with a clear message.

Useful phrases for interviews

  • “I keep detection and handling separate: the service throws a domain exception, and a global handler turns it into an HTTP response.”
  • “We return a ProblemDetail with a stable error code and a trace ID, and we never expose stack traces to clients.”
  • “Bean Validation covers the format of the input, the service enforces business rules, and the database constraint is the final guarantee.”
  • “One thing that often surprises people is that @Transactional doesn’t roll back on checked exceptions by default.”
  • “The existence check is just for a friendly error; the unique index is what actually prevents duplicates under concurrency.”
  • “Business errors are logged at WARN without a stack trace; unexpected ones are logged at ERROR and raise an alert.”
  • “Errors from filters and Spring Security never reach the controller advice, so we render them in the same format with an entry point and an access-denied handler.”
  • “Clients should branch on a stable error code, never on the message text.”
  • “Since Spring 6.1, validation of controller method parameters is built in and fails with a 400 instead of a 500.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.