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

@ResponseStatus

Pick the status.

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

We want Book Not Found Exception to become four oh four, not five hundred. The quickest way is one annotation.

  • Not 500
  • 404 instead
  • One annotation

One annotation

At Response Status, on the exception class, picks the status for it. Now, whenever it's thrown, Spring answers four oh four. Run it. Book nine now gives a clean four oh four.

BookNotFoundException.javajava
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {

    public BookNotFoundException(long id) {
        super("Book " + id + " was not found");
    }
}
Output
HTTP/1.1 404
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 BookController.java
@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);
    }
}
Also uses _curl.sh
curl -i localhost:8080/books/9 | head -1

ResponseStatusException

For a quick one off, throw a Response Status Exception. It takes a status, and a reason. No custom class needed. Run it. Book nine gives four oh four again.

BookController.javajava
@RestController
public class BookController {

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

    @GetMapping("/books/{id}")
    public String one(@PathVariable long id) {
        String title = titles.get(id);
        if (title == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No book " + id);
        }
        return title;
    }
}
Output
HTTP/1.1 404
Also uses _curl.sh
curl -i localhost:8080/books/9 | head -1

Which to choose?

At Response Status is simple, but it gives the same default body as before. Response Status Exception is handy, for one off cases. For full control of the body, use a global handler. That's next.

keyvalue
@ResponseStatussimple, fixed status
ResponseStatusExceptionquick one-offs
Global handlerfull control (next)
Allno more wrong 500s

Summary

At Response Status maps an exception to a status code. Response Status Exception does it inline. Next, one handler for the whole app.

Key takeaways
  • @ResponseStatus(NOT_FOUND)
  • ResponseStatusException
  • 404, not 500
Next up: @RestControllerAdvice — handle errors everywhere