🎓 A1Learner
🔍
0 of 50 lessons completed

Custom Error Answers

A custom error answer is a small JSON object the app returns when something goes wrong. It carries a status and a message so the client knows what happened.

The error record

This record holds the two fields of an error answer. Jackson turns it into JSON.

public record ErrorResponse(int status, String message) {
}

Return the error answer

This method answers IllegalArgumentException with an ErrorResponse. The status is 400.

@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ErrorResponse> handleBadRequest(IllegalArgumentException error) {
    return ResponseEntity.badRequest().body(new ErrorResponse(400, error.getMessage()));
}

Example

package com.example.demo;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    public record ErrorResponse(int status, String message) {
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorResponse> handleBadRequest(IllegalArgumentException error) {
        return ResponseEntity.badRequest().body(new ErrorResponse(400, error.getMessage()));
    }
}

@RestController
class TaskController {

    @PostMapping("/tasks")
    public String addTask(@RequestBody TaskForm form) {
        if (form.title() == null || form.title().isBlank()) {
            throw new IllegalArgumentException("Task title must not be empty");
        }
        return "Saved";
    }

    record TaskForm(String title, boolean done) {
    }
}

Key points

  • An ErrorResponse record holds a status and a message.
  • A record is a short Java class that holds data.
  • The handler builds an ErrorResponse when an error happens.
  • The client reads the message to learn what went wrong.
  • The status number matches the HTTP status of the answer.

In this example, the record ErrorResponse holds a status and a message. The class carries @ControllerAdvice, so it serves every controller. The method handles IllegalArgumentException. It builds an ErrorResponse with status 400 and the error message. The client receives the JSON object with both fields. A small controller in the example throws the error when a title is blank.

Note

Keep the message short and plain for the client.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does an ErrorResponse carry?