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.
When we execute the service with a GET request to a nonexistent ;todo (http://localhost:8080/users/Jack/todos/222), we get the response shown in the following code snippet:
{
"timestamp": 1484029048788,
"status": 500,
"error": "Internal Server Error",
"exception":
"com.mastering.spring.springboot.bean.TodoNotFoundException",
"message": "Todo Not Found",
"path": "/users/Jack/todos/222"
}
As we can see, a clear exception response is sent back to the service consumer. However, there is one thing that can be improved further--the response status. When a resource is not found, it is recommended that you return a 404 - Resource Not Found status. We will look at how to customize the response ;status ;in the next example.