Throwing a custom exception

Let's create a custom exception and throw it from a service. Take a look at the following code:

    public class TodoNotFoundException extends RuntimeException {      public TodoNotFoundException(String msg) {        super(msg);      }    }

It's a very simple piece of code that defines ;TodoNotFoundException .

Now let's enhance our TodoController ;class to throw TodoNotFoundException when a todo with a given ID is not found:

    @GetMapping(path = "/users/{name}/todos/{id}")    public Todo retrieveTodo(@PathVariable String name,     @PathVariable int id) {      Todo todo = todoService.retrieveTodo(id);      if (todo == null) {        throw new TodoNotFoundException("Todo Not Found");       }     return todo;    }

If todoService returns a null todo, we throw ;TodoNotFoundException ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.