🎓 A1Learner
🔍
0 of 50 lessons completed

Exceptions in Controllers

An exception in a controller stops the request with an error. The controller throws it when the task is missing.

An exception that names the missing task

The exception carries the missing id in its message.

public class TaskNotFoundException extends RuntimeException {
    public TaskNotFoundException(Long id) {
        super("Task not found: " + id);
    }
}

Throw it when the task is missing

orElseThrow runs the throw when the box is empty.

Task task = repository.findById(id)
        .orElseThrow(() -> new TaskNotFoundException(id));

Example

package com.example.demo;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    private final TaskRepository repository;

    public TaskController(TaskRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/tasks/{id}")
    public TaskView oneTask(@PathVariable Long id) {
        Task task = repository.findById(id)
                .orElseThrow(() -> new TaskNotFoundException(id));
        return new TaskView(task.getTitle(), task.isDone());
    }

    public static class TaskNotFoundException extends RuntimeException {
        public TaskNotFoundException(Long id) {
            super("Task not found: " + id);
        }
    }

    public record TaskView(String title, boolean done) {
    }
}

Key points

  • A missing task has no answer to send.
  • The controller throws an exception instead.
  • TaskNotFoundException extends RuntimeException.
  • RuntimeException needs no throws line on the method.
  • The exception carries the missing id in its message.
  • Spring answers 500 until a handler is added.

In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The oneTask method reads one task with findById. When the id is missing, orElseThrow throws TaskNotFoundException. The exception carries the missing id in its message. The first exchange shows the 500 answer for id 99. The second exchange shows the task with id 2.

Note

A later lesson teaches how to turn this into a 404 answer.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the controller throw when the id is missing?