Skip to content

2. Custom error message

Stratis Dermanoutsos edited this page Sep 18, 2025 · 3 revisions

We saw earlier, in Basic usage that each exception type has a default message.

1. Default behaviour

For example, the 404 exception results in a response similar to the following:

{
  "type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "Content not found.",
  "instance": "/users/12",
  "traceId": "00-f3e52009f0966d717f93c9653ed45e26-750dad4218610f7f-00",
  "method": "GET",
  "requestId": "0HNE94J42PNH8:00000001"
}

This is the result of:

throw new NotFoundRestException();

2. Custom messages

If we instead do the following:

throw new NotFoundRestException("The user was not found.");

we will get this response:

{
  "type": "https://www.rfc-editor.org/rfc/rfc9110.html#name-404-not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "The user was not found.",
  "instance": "/users/12",
  "traceId": "00-f3e52009f0966d717f93c9653ed45e26-750dad4218610f7f-00",
  "method": "GET",
  "requestId": "0HNE94J42PNH8:00000001"
}

Clone this wiki locally