# Problem Details for Errors — Spring Boot

Source: https://www.skillbyai.com/en/spring-boot/w-errors

> Consistent, standard error responses.

## @RestControllerAdvice and ProblemDetail

A `@RestControllerAdvice` class handles exceptions for all controllers in one place. Returning Spring's `ProblemDetail` produces **RFC 9457 problem details** JSON (`type`, `title`, `status`, `detail`, `instance`), a standard format clients can parse consistently. Map domain exceptions (not found, conflict, forbidden) to the right status codes, and never leak stack traces or internal messages to clients.

## An exception handler returning ProblemDetail

This file is from a demo "shop" service generated by start.spring.io for Spring Boot 4.1.1 and Java 21 (Temurin 21.0.12), built with Maven 3.9.16; the project compiled and its tests passed. ProductNotFoundException becomes a 404 problem-details response with a clear title and detail.

```java
package com.example.shop;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ApiErrors {
    @ExceptionHandler(ProductNotFoundException.class)
    public ProblemDetail notFound(ProductNotFoundException e) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        pd.setTitle("Product not found");
        return pd;                                   // RFC 9457 problem details JSON
    }
}
```

## Requesting a missing product, run

I packaged the demo with mvn package, started it with java -jar on port 8085 and called it with curl; the output is copied from that run. The handler returns status 404 with the problem-details fields.

```bash
curl -s -w " [%{http_code}]" localhost:8085/api/products/99
```

Output:

```
{"detail":"Product 99 not found","instance":"/api/products/99","status":404,"title":"Product not found"} [404]
```

**Quiz:** What is RFC 9457?

- [x] A standard JSON format for HTTP API problem details
- [ ] A Java version
- [ ] A database isolation level
- [ ] A logging library

*Answer:* A standard JSON format for HTTP API problem details. Standard, parseable errors.
