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 ...