Answering 404
A 404 answer tells the client that the asked-for task does not exist. ResponseStatusException is a Spring exception that carries a status and a reason.
Throw a 404
This line throws a 404 when no task matches the id. The reason names what was missing.
Task task = repository.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Task not found"));The imports
These two imports bring in the exception and the status. Both come from Spring.
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;Example
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
public class TaskController {
private final TaskRepository repository;
public TaskController(TaskRepository repository) {
this.repository = repository;
}
@GetMapping("/tasks/{id}")
public Task getTask(@PathVariable Long id) {
return repository.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Task not found"));
}
}Key points
- 404 means the thing asked for was not found.
- ResponseStatusException carries a status and a reason.
- Throw it when a task id has no match.
- Spring turns the exception into a 404 answer.
- The reason text explains what was missing.
In this example, the controller asks the repository for the task id. The findById call returns an empty result when no task matches. The orElseThrow call then throws a ResponseStatusException. The exception carries status 404 and the reason Task not found. Spring turns it into a 404 answer for the client.
Note
Use the same not-found answer for every missing task.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which exception answers a missing task with 404?