Skip to content

Spring Boot Exception Controller Advice

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot @ControllerAdvice Not Catching. We cover key concepts, practical examples, and best practices.

The Problem

@ControllerAdvice does not catch exceptions thrown by controllers, and custom error responses are ignored.

Quick Fix

Create @ControllerAdvice class

Wrong:

public class GlobalExceptionHandler {
    // No @ControllerAdvice
}

Output:

Advice not applied

Right:

@RestControllerAdvice
public class GlobalExceptionHandler { }

Output:

Advice applied globally

Define exception handler methods

Wrong:

@RestControllerAdvice
public class GlobalHandler {
    // No handler methods
}

Output:

Exceptions not caught

Right:

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleNotFound(ResourceNotFoundException ex) {
    return ResponseEntity.status(404).body(ex.getMessage());
}

Output:

Exceptions caught globally

Set response status

Wrong:

@ExceptionHandler(Exception.class)
public String handle(Exception ex) { return ex.getMessage(); }

Output:

Always returns 200

Right:

@ExceptionHandler(Exception.class)
public ResponseEntity<?> handle(Exception ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(Map.of("error", ex.getMessage()));
}

Output:

Correct HTTP status

Prevention

  • Annotate the class with @RestControllerAdvice
  • Add @ExceptionHandler methods for each exception type
  • Return proper ResponseEntity with HTTP status

Common Mistakes with boot exception controller advice

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between @ControllerAdvice and @RestControllerAdvice?

@RestControllerAdvice combines @ControllerAdvice and @ResponseBody for JSON responses.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro