AI Hints
Home›Spring Boot Tutorial›Validation Errors, Custom Exceptions and @ResponseStatus
Spring Boot · Lesson 77 of 120

Custom Exceptions

Name your problems.

⏱ 2 min read▶ Video at 1:43:51🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Some problems aren't about bad input. The input is fine, but the book doesn't exist. A custom exception gives that problem a clear name.

  • Input is fine
  • The book doesn't exist
  • Give it a name

BookNotFoundException

Our exception extends Runtime Exception, so methods don't need to declare it. The constructor builds a clear message, with the id.

BookNotFoundException.javajava
public class BookNotFoundException extends RuntimeException {

    public BookNotFoundException(long id) {
        super("Book " + id + " was not found");
    }
}

Thrown by the service

The service looks up a title. If there's none, it throws our exception. The service knows nothing about HTTP. It just says what went wrong.

BookService.javajava
@Service
public class BookService {

    private final Map<Long, String> titles = Map.of(1L, "Dune", 2L, "Circe");

    public String title(long id) {
        String title = titles.get(id);
        if (title == null) {
            throw new BookNotFoundException(id);
        }
        return title;
    }
}

Without any handling

The controller just calls the service. Run it. Book one works. But book nine throws, and nobody catches it. So Spring answers five hundred, as if the server crashed. That's wrong. A missing book is not a server error.

BookController.javajava
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) { this.service = service; }

    @GetMapping("/books/{id}")
    public String one(@PathVariable long id) {
        return service.title(id);
    }
}
Output
$ curl localhost:8080/books/1
Dune
$ curl localhost:8080/books/9
{
  "timestamp":"2026-11-25T16:28:03.227Z",
  "status":500,
  "error":"Internal Server Error",
  "path":"/books/9"
}
Also uses BookNotFoundException.java
public class BookNotFoundException extends RuntimeException {

    public BookNotFoundException(long id) {
        super("Book " + id + " was not found");
    }
}
Also uses BookService.java
@Service
public class BookService {

    private final Map<Long, String> titles = Map.of(1L, "Dune", 2L, "Circe");

    public String title(long id) {
        String title = titles.get(id);
        if (title == null) {
            throw new BookNotFoundException(id);
        }
        return title;
    }
}
Also uses _curl.sh
curl localhost:8080/books/1
curl localhost:8080/books/9
Also uses _log
none

Summary

Custom exceptions name your problems, like Book Not Found Exception. Uncaught, they become five hundred, which is wrong. Next, at Response Status.

Key takeaways
  • extends RuntimeException
  • Clear names
  • Uncaught → 500
Next up: @ResponseStatus — pick the status