Problem statement
Spring Boot: Global Error Response Standardizer
Build a global error handler that converts every failure in a book lookup API into one standard error body.
Requirements
GlobalErrorHandler
Implement the class so that it intercepts errors raised anywhere in the application from this one place and shapes every error response as follows.
The standard error body:
- Every error response is a JSON object with exactly five fields (timestamp, status, code, message, and path) and no other field; all three cases below return this identical shape
- timestamp carries the moment the response was produced and is never empty
- status repeats the numeric HTTP status code of the response
- path carries the path of the request that failed
- No error response ever contains a stack trace, an exception class name, or an error field
The three cases:
- When the body of POST /books fails validation (title missing, empty, or whitespace-only), return 400 Bad Request with code VALIDATION_ERROR and message "Title must not be blank"
- When GET /books/{id} addresses an id no book has, return 404 Not Found with code NOT_FOUND and message "Book not found with id: " followed by the requested id
- When any other unhandled error occurs (GET /reports/crash always raises one), return 500 Internal Server Error with code INTERNAL_ERROR and message "An unexpected error occurred"; the original error's own text never appears anywhere in the response
Sample Requests & Responses
Expand to view details on sample requests and responses.
GET /books/1
Response (200 OK):
{
"id": 1,
"title": "The Silent Library",
"author": "Mara Ellison"
}
POST /books
Request:
{
"title": "",
"author": "Mara Ellison"
}
Response (400 Bad Request):
{
"timestamp": "2026-07-30T09:58:59.103127",
"status": 400,
"code": "VALIDATION_ERROR",
"message": "Title must not be blank",
"path": "/books"
}
GET /books/99
Response (404 Not Found):
{
"timestamp": "2026-07-30T09:58:44.786231",
"status": 404,
"code": "NOT_FOUND",
"message": "Book not found with id: 99",
"path": "/books/99"
}
GET /reports/crash
Response (500 Internal Server Error):
{
"timestamp": "2026-07-30T09:58:45.100222",
"status": 500,
"code": "INTERNAL_ERROR",
"message": "An unexpected error occurred",
"path": "/reports/crash"
}
