# Error handling

> Show errors to the user for full page requests, htmx requests and REST APIs; error pages built from Shadleaf components, and an error toast for a failed htmx request.

Source: https://shadleaf.dev/1.2.0/guides/error-handling/

An application built with Shadleaf typically receives three kinds of requests, and each one needs a different way of
reporting errors:

| Request                      | What the user should see                   | Handled by                                                           |
|------------------------------|--------------------------------------------|----------------------------------------------------------------------|
| Full page (`@Controller`)    | An error page inside the application shell | Spring Boot's `error/<status>.html` templates                        |
| htmx (`@Controller` + htmx)  | An error toast, the page stays untouched   | A `HandlerExceptionResolver` that sends the `sl-toast` event         |
| REST API (`@RestController`) | A JSON error response                      | [Error Handling Spring Boot Starter](#rest-controllers)              |

The three approaches complement each other and can be used together in one application.

> **Tip: Looking for form validation?**
>
> A form the user filled in wrongly is no error in the sense of this page: the controller renders the form again, with
> its errors next to the fields. See [Form errors](https://shadleaf.dev/1.2.0/components/form-errors.md) and
> [Forms with htmx](https://shadleaf.dev/1.2.0/guides/forms-htmx.md), and [Validating as you type](https://shadleaf.dev/1.2.0/components/form.md#validating-as-you-type) to
> check each field on the server while the user edits it.

## Error pages

Spring Boot renders a template from the `error` directory when a full page request fails. It looks for the exact
status code first, and falls back to the series:

```
src/main/resources/templates/error/
├── 403.html   # access denied
├── 404.html   # unknown URL
├── 4xx.html   # any other client error
└── 5xx.html   # any server error
```

Best practices:

- **Render error pages inside the application shell**, using the same layout as your other pages, so the user keeps
  the navigation and can easily continue.
- **Provide at least `4xx.html` and `5xx.html`**, so the user never sees Spring Boot's "Whitelabel Error Page". Add
  dedicated pages for the status codes that need a specific message, typically `403` and `404`.
- **Tell the user what to do next**: go back home, sign in with another account, contact the administrator, …
- **Show the technical details only when Spring Boot is configured to include them**, so you can enable them locally
  and keep them hidden in production (see [Technical details](#technical-details)).

The examples below assume a `layout/main :: layout(pageTitle, content)` template that renders the page title as the
`h1`, as in the [application shell](https://shadleaf.dev/1.2.0/components/application-shell.md) and sample-02. Each page puts an
[empty state](https://shadleaf.dev/1.2.0/components/empty.md) where the content would be, with an icon, what went wrong and a way out. Copy
them into a new project and adapt the layout call and the texts.

This is what the `404` page shows below its title:

**Example: On an error page.** The content of a 404 page, from the Error handling guide.

```html
<sl:empty border>
  <sl:empty-header>
    <sl:empty-media variant="icon"><sl:icon name="file-question-mark"/></sl:empty-media>
    <sl:empty-title level="2">This page does not exist</sl:empty-title>
    <sl:empty-description>
      The address may be mistyped, or the page has moved. Check the address, or start again from the home page.
    </sl:empty-description>
  </sl:empty-header>
  <sl:empty-content>
    <sl:button as="a" th:href="@{/}">
      <sl:slot name="icon-start"><sl:icon name="house"/></sl:slot>
      Go to the home page
    </sl:button>
  </sl:empty-content>
</sl:empty>
```

```html title="src/main/resources/templates/error/404.html"
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sl="https://shadleaf.dev/sl"
      th:replace="~{layout/main :: layout('Page not found', ~{::#page-content})}">
<body>
<div id="page-content">
  <sl:empty border>
    <sl:empty-header>
      <sl:empty-media variant="icon"><sl:icon name="file-question-mark"/></sl:empty-media>
      <sl:empty-title level="2">This page does not exist</sl:empty-title>
      <sl:empty-description>
        The address may be mistyped, or the page has moved. Check the address, or start again from the home page.
      </sl:empty-description>
    </sl:empty-header>
    <sl:empty-content>
      <sl:button as="a" th:href="@{/}">
        <sl:slot name="icon-start"><sl:icon name="house"/></sl:slot>
        Go to the home page
      </sl:button>
    </sl:empty-content>
  </sl:empty>
</div>
</body>
</html>
```

The `403` page offers to sign out, so the user can sign in with another account. It posts to Spring Security's default
logout endpoint; `th:action` adds the CSRF token.

```html title="src/main/resources/templates/error/403.html"
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sl="https://shadleaf.dev/sl"
      th:replace="~{layout/main :: layout('Access denied', ~{::#page-content})}">
<body>
<div id="page-content">
  <sl:empty border>
    <sl:empty-header>
      <sl:empty-media variant="icon"><sl:icon name="shield-x"/></sl:empty-media>
      <sl:empty-title level="2">You do not have access to this page</sl:empty-title>
      <sl:empty-description>
        Sign out and sign in again with another account, or ask the administrator to give your account the roles it needs.
      </sl:empty-description>
    </sl:empty-header>
    <sl:empty-content>
      <form method="post" th:action="@{/logout}">
        <sl:button type="submit" variant="outline">
          <sl:slot name="icon-start"><sl:icon name="log-out"/></sl:slot>
          Sign out
        </sl:button>
      </form>
      <sl:button as="a" variant="link" th:href="@{/}">Go to the home page</sl:button>
    </sl:empty-content>
  </sl:empty>
</div>
</body>
</html>
```

The pages for a whole series show the status and its reason phrase (`status` and `error`, which Spring Boot always
puts in the model), and the technical details:

```html title="src/main/resources/templates/error/4xx.html"
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sl="https://shadleaf.dev/sl"
      th:replace="~{layout/main :: layout('Error', ~{::#page-content})}">
<body>
<div id="page-content">
  <sl:empty border>
    <sl:empty-header>
      <sl:empty-media variant="icon"><sl:icon name="circle-alert"/></sl:empty-media>
      <sl:empty-title level="2">[[${status}]] [[${error}]]</sl:empty-title>
      <sl:empty-description>
        The request could not be handled. Go back and try again, or contact the administrator if it keeps happening.
      </sl:empty-description>
    </sl:empty-header>
    <sl:empty-content>
      <sl:button as="a" th:href="@{/}">
        <sl:slot name="icon-start"><sl:icon name="house"/></sl:slot>
        Go to the home page
      </sl:button>
    </sl:empty-content>
  </sl:empty>
  <th:block th:replace="~{error/error-details :: error-details}"></th:block>
</div>
</body>
</html>
```

```html title="src/main/resources/templates/error/5xx.html"
<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sl="https://shadleaf.dev/sl"
      th:replace="~{layout/main :: layout('Error', ~{::#page-content})}">
<body>
<div id="page-content">
  <sl:empty border>
    <sl:empty-header>
      <sl:empty-media variant="icon"><sl:icon name="server-crash"/></sl:empty-media>
      <sl:empty-title level="2">Something went wrong on our side</sl:empty-title>
      <sl:empty-description>
        It is not your fault, and the error has been logged. Try again in a moment, or contact the administrator if it
        keeps happening.
      </sl:empty-description>
    </sl:empty-header>
    <sl:empty-content>
      <sl:button as="a" th:href="@{/}">
        <sl:slot name="icon-start"><sl:icon name="house"/></sl:slot>
        Go to the home page
      </sl:button>
    </sl:empty-content>
  </sl:empty>
  <th:block th:replace="~{error/error-details :: error-details}"></th:block>
</div>
</body>
</html>
```

When Spring Security protects the application, a visitor who is not signed in must be able to see the error pages too.
Spring Security also checks the error dispatch, so without this an unknown URL sends them to the sign-in page instead:

```java
http.authorizeHttpRequests(requests -> requests
    .dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()
    // ... your other rules
);
```

### Technical details

Spring Boot adds the exception's class, its message and its stack trace to the model of the error page (`exception`,
`message` and `trace`) only when it is configured to. Never expose them in production. Keep them hidden by default
and enable them only in a local profile:

```yaml title="application.yml"
spring:
  web:
    error:
      include-message: never
      include-stacktrace: never
```

```yaml title="application-local.yml"
spring:
  web:
    error:
      include-message: always
      include-exception: true
      include-stacktrace: always
```

A [collapsible](https://shadleaf.dev/1.2.0/components/collapsible.md) in its [panel](https://shadleaf.dev/1.2.0/components/collapsible.md#panel) variant shows them
below the empty state when they are there, and renders nothing in production. The stack trace goes in a
[code block](https://shadleaf.dev/1.2.0/components/code-block.md), which keeps its line breaks, scrolls its long lines and lets the user copy
it into a bug report. Keep it in a template of its own, so `4xx.html` and `5xx.html` share it. Spring Boot only looks
up `error/<status>` and `error/<series>`, so the file can sit next to them:

```html title="src/main/resources/templates/error/error-details.html"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sl="https://shadleaf.dev/sl">
<body>
<th:block th:fragment="error-details">
  <sl:collapsible th:if="${exception != null or message != null or trace != null}"
                  variant="panel"
                  class="error-details">
    <sl:collapsible-trigger>Technical details</sl:collapsible-trigger>
    <sl:collapsible-content>
      <!--/* The trace starts with the exception and its message; without it, show those. */-->
      <sl:code-block th:if="${trace}">[[${trace}]]</sl:code-block>
      <th:block th:unless="${trace}">
        <p th:if="${exception}"><code th:text="${exception}"></code></p>
        <p th:if="${message}" th:text="${message}"></p>
      </th:block>
    </sl:collapsible-content>
  </sl:collapsible>
</th:block>
</body>
</html>
```

The panel draws the full-width trigger, the chevron and the muted background while it is open. Your own stylesheet
adds some space above it, sets the code block apart from the muted panel, and limits the height of the stack trace,
which is long, so it scrolls:

```css
.error-details {
  margin-block-start: 1.5rem;
}

.error-details .code-block {
  background: var(--background);
}

.error-details .code-block-content {
  max-block-size: 30rem;
  font-size: 0.75rem;
}
```

With the details enabled, the `5xx` page looks like this (the details are open here, on the page they start closed):

**Example: On an error page, with the technical details.** The content of a 5xx page with Spring Boot's error details enabled, from the Error handling guide. The details are open here; on the page they start closed.

```html
<sl:empty border>
  <sl:empty-header>
    <sl:empty-media variant="icon"><sl:icon name="server-crash"/></sl:empty-media>
    <sl:empty-title level="2">Something went wrong on our side</sl:empty-title>
    <sl:empty-description>
      It is not your fault, and the error has been logged. Try again in a moment, or contact the administrator if
      it keeps happening.
    </sl:empty-description>
  </sl:empty-header>
  <sl:empty-content>
    <sl:button as="a" th:href="@{/}">
      <sl:slot name="icon-start"><sl:icon name="house"/></sl:slot>
      Go to the home page
    </sl:button>
  </sl:empty-content>
</sl:empty>
<sl:collapsible th:if="${exception != null or message != null or trace != null}"
                variant="panel"
                class="error-details">
  <sl:collapsible-trigger>Technical details</sl:collapsible-trigger>
  <sl:collapsible-content>
    <sl:code-block th:if="${trace}">[[${trace}]]</sl:code-block>
    <th:block th:unless="${trace}">
      <p th:if="${exception}"><code th:text="${exception}"></code></p>
      <p th:if="${message}" th:text="${message}"></p>
    </th:block>
  </sl:collapsible-content>
</sl:collapsible>
```

## htmx requests

htmx 4 swaps error responses (4xx/5xx) into the target, so a failing htmx request would put a whole error page in
the middle of your page (see [Forms with htmx](https://shadleaf.dev/1.2.0/guides/forms-htmx.md#swapping)). Instead of handling this in every controller, register one
`HandlerExceptionResolver` that turns the exception of any htmx request into an error
[toast](https://shadleaf.dev/1.2.0/components/toast.md), and prevents the swap with `HX-Reswap: none`. htmx processes the `HX-Trigger` header
of error responses too, and the `<sl:toaster>` in your layout shows the toast.

The resolver has to decide which status to use and which message is safe to show. Exception messages often contain
internal details (SQL, constraint names, class names, …), so by default the user only sees a generic message. There
are two ways to tell the resolver otherwise, each in a variant for an application in one language (a) and in several
(b):

| Option                                                                                              | Use when                                | A user-facing error is…                                                                        |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------|------------------------------------------------------------------------------------------------|
| [1a: Marker interface](#option-1a-marker-interface)                                                 | Only Thymeleaf pages, one language      | An exception that implements `UserFacingException`                                             |
| [1b: Marker interface with translations](#option-1b-marker-interface-with-translations)             | Only Thymeleaf pages, several languages | The same, with a message key instead of a text                                                 |
| [2a: Error Handling Starter](#option-2a-error-handling-starter)                                     | Also a REST API, one language           | An exception mapped to a status via `@ResponseStatus`, `ResponseStatusException` or properties |
| [2b: Error Handling Starter with translations](#option-2b-error-handling-starter-with-translations) | Also a REST API, several languages      | The same, with a message key named after the starter's error code                              |

In every option, any other exception shows the toast "An unexpected error occurred." and, as a `5xx`, is logged as an
error.

### Option 1a: marker interface

Without extra dependencies, mark the exceptions that should be reported to the user with an interface that provides
the HTTP status and a message for the user. The user message is kept separate from the exception message, so the
latter can stay technical for the logs.

  1. Add the marker interface:

     ```java title="UserFacingException.java"
     /**
      * Marks an exception that is reported to the user. Exceptions without this marker are shown
      * with a generic message.
      */
     public interface UserFacingException {

       /** The HTTP status of the response. */
       HttpStatusCode getStatusCode();

       /**
        * The message shown to the user. Unlike {@link Throwable#getMessage()}, which ends up in the
        * logs, it must not contain technical details.
        */
       String getUserMessage();
     }
     ```
  2. Add the resolver:

     ```java title="HtmxErrorToastResolver.java"
     /**
      * Shows exceptions of htmx requests as an error toast instead of swapping the error
      * responses. Only the message of a {@link UserFacingException} is shown; any other exception
      * gets a generic message.
      */
     class HtmxErrorToastResolver implements HandlerExceptionResolver {

       private static final Logger LOGGER = LoggerFactory.getLogger(HtmxErrorToastResolver.class);
       private static final String GENERIC_MESSAGE = "An unexpected error occurred.";

       @Override
       public ModelAndView resolveException(
           HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
         boolean htmx = "true".equals(request.getHeader("HX-Request"));
         if (response.isCommitted() || (!htmx && !(ex instanceof UserFacingException))) {
           return null;
         }

         HttpStatusCode status = HttpStatus.INTERNAL_SERVER_ERROR;
         String message = GENERIC_MESSAGE;
         if (ex instanceof UserFacingException userFacing) {
           status = userFacing.getStatusCode();
           message = userFacing.getUserMessage();
         } else if (ex instanceof ErrorResponse errorResponse) {
           // Spring's own exceptions (an unknown URL, a ResponseStatusException) keep their status
           status = errorResponse.getStatusCode();
         }
         if (status.is5xxServerError()) {
           LOGGER.error("Request {} {} failed", request.getMethod(), request.getRequestURI(), ex);
         }

         if (!htmx) {
           // Full page request: let Spring Boot render the matching error/<status>.html page
           try {
             response.sendError(status.value(), message);
           } catch (IOException e) {
             throw new UncheckedIOException(e);
           }
           return new ModelAndView();
         }

         // Shown by <sl:toaster>, which listens for the sl-toast event
         response.setStatus(status.value());
         response.setHeader("HX-Trigger", "{\"sl-toast\":" + Toast.error(message).toJson() + "}");
         response.setHeader("HX-Reswap", "none");
         // An empty ModelAndView marks the exception as handled without rendering a view
         return new ModelAndView();
       }
     }
     ```
  3. Register it right after Spring's `ExceptionHandlerExceptionResolver`. That way your own `@ExceptionHandler`
     methods and `@ControllerAdvice` classes still take precedence, but the resolver runs before
     `ResponseStatusExceptionResolver` and `DefaultHandlerExceptionResolver` turn the exception into an error page:

     ```java title="HtmxErrorToastConfiguration.java"
     @Configuration(proxyBeanMethods = false)
     class HtmxErrorToastConfiguration implements WebMvcConfigurer {

       @Override
       public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
         int index = 0;
         for (int i = 0; i < resolvers.size(); i++) {
           if (resolvers.get(i) instanceof ExceptionHandlerExceptionResolver) {
             index = i + 1;
           }
         }
         resolvers.add(index, new HtmxErrorToastResolver());
       }
     }
     ```
  4. Implement the marker on your own exceptions:

     ```java title="TeamNotEmptyException.java"
     public class TeamNotEmptyException extends RuntimeException implements UserFacingException {

       public TeamNotEmptyException(long teamId) {
         super("Team " + teamId + " is still referenced by members");
       }

       @Override
       public HttpStatusCode getStatusCode() {
         return HttpStatus.CONFLICT;
       }

       @Override
       public String getUserMessage() {
         return "The team still has members and cannot be deleted";
       }
     }
     ```

Things to know about this option:

- Only `getUserMessage()` is shown to the user. `getMessage()` stays technical and is what you see in the logs and
  stack traces.
- Only the marker decides what the user reads. A `ResponseStatusException`, or any of Spring's own exceptions, keeps
  its status but shows the generic message. An exception annotated with `@ResponseStatus` gets a `500`.
- The resolver also sets the status of a `UserFacingException` for full page requests, so Spring Boot renders the
  matching [error page](#error-pages) (`4xx.html` for a `409`) instead of `5xx.html`.

### Option 1b: marker interface with translations

For an application in several languages, the exception names a message key instead of returning the text. Spring
already has an interface for that, `MessageSourceResolvable`: message codes, arguments and a default message, which
the `MessageSource` turns into text in the user's language. Start from option 1a, and change it like this:

  1. Make the marker extend `MessageSourceResolvable` instead of declaring `getUserMessage()`:

     ```java title="UserFacingException.java"
     /**
      * Marks an exception that is reported to the user, with the message key of what the user
      * reads. Exceptions without this marker are shown with a generic message.
      */
     public interface UserFacingException extends MessageSourceResolvable {

       /** The HTTP status of the response. */
       HttpStatusCode getStatusCode();
     }
     ```
  2. Give the resolver the `MessageSource`, and resolve both messages in the locale of the request:

     ```java title="HtmxErrorToastResolver.java"
     class HtmxErrorToastResolver implements HandlerExceptionResolver {

       // LOGGER and GENERIC_MESSAGE as in option 1a

       private final MessageSource messageSource;

       HtmxErrorToastResolver(MessageSource messageSource) {
         this.messageSource = messageSource;
       }

       @Override
       public ModelAndView resolveException(
           HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
         // the htmx check as in option 1a

         Locale locale = RequestContextUtils.getLocale(request);
         HttpStatusCode status = HttpStatus.INTERNAL_SERVER_ERROR;
         String message = messageSource.getMessage("error.unexpected", null, GENERIC_MESSAGE, locale);
         if (ex instanceof UserFacingException userFacing) {
           status = userFacing.getStatusCode();
           message = messageSource.getMessage(userFacing, locale);
         } else if (ex instanceof ErrorResponse errorResponse) {
           status = errorResponse.getStatusCode();
         }

         // logging, the error page and the toast as in option 1a
       }
     }
     ```
  3. Pass it in from the configuration class, which can inject it:

     ```java title="HtmxErrorToastConfiguration.java"
     @Configuration(proxyBeanMethods = false)
     class HtmxErrorToastConfiguration implements WebMvcConfigurer {

       private final MessageSource messageSource;

       HtmxErrorToastConfiguration(MessageSource messageSource) {
         this.messageSource = messageSource;
       }

       @Override
       public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
         // find the index as in option 1a
         resolvers.add(index, new HtmxErrorToastResolver(messageSource));
       }
     }
     ```
  4. Let your exceptions give the key, its arguments, and the text to show when no language has the key:

     ```java title="TeamNotEmptyException.java"
     public class TeamNotEmptyException extends RuntimeException implements UserFacingException {

       private final String teamName;

       public TeamNotEmptyException(long teamId, String teamName) {
         super("Team " + teamId + " is still referenced by members");
         this.teamName = teamName;
       }

       @Override
       public HttpStatusCode getStatusCode() {
         return HttpStatus.CONFLICT;
       }

       @Override
       public String[] getCodes() {
         return new String[] {"error.team-not-empty"};
       }

       @Override
       public Object[] getArguments() {
         return new Object[] {teamName};
       }

       @Override
       public String getDefaultMessage() {
         return "The team still has members and cannot be deleted";
       }
     }
     ```
  5. Add the messages, in every language:

     ```properties title="messages.properties"
     error.unexpected=An unexpected error occurred.
     # {0}: the name of the team
     error.team-not-empty=Team {0} still has members and cannot be deleted
     ```

     ```properties title="messages_nl.properties"
     error.unexpected=Er is een onverwachte fout opgetreden.
     # {0}: the name of the team
     error.team-not-empty=Team {0} heeft nog leden en kan niet verwijderd worden
     ```

Things to know about this option:

- `RequestContextUtils.getLocale(request)` asks the application's `LocaleResolver`, so the toast follows the same
  language as the page: the browser's `Accept-Language` by default, or the language the user picked.
- The message is a `MessageFormat` pattern as soon as it has arguments: write an apostrophe twice (`''`) there.
- The texts of the error pages themselves go in message keys too, as on any other page: `#{error.not-found.title}`.
  The [Translating](https://shadleaf.dev/1.2.0/guides/translating.md) guide covers Shadleaf's own texts, which the toaster's close button uses.

### Option 2a: Error Handling Starter

If the application already uses the [Error Handling Spring Boot Starter](#rest-controllers) for its REST API, reuse its
`HttpStatusMapper` and `ErrorMessageMapper` beans. htmx requests then follow the same rules and the same
`error.handling` configuration as the REST controllers, and you can throw any exception:

| The exception…                                              | Status                | Message shown                    |
|-------------------------------------------------------------|-----------------------|----------------------------------|
| is configured in `error.handling.messages`                  | as resolved below     | the configured message           |
| is a `ResponseStatusException` (or another `ErrorResponse`) | its status            | its detail (4xx only)            |
| is configured in `error.handling.http-statuses`             | the configured status | the exception message (4xx only) |
| is annotated with `@ResponseStatus`                         | the annotated status  | the exception message (4xx only) |
| anything else                                               | `500`                 | the generic message              |

  1. Add the resolver:

     ```java title="HtmxErrorToastResolver.java"
     /**
      * Shows exceptions of htmx requests as an error toast instead of swapping the error
      * responses. The status and message are resolved like the Error Handling Spring Boot Starter
      * does for REST controllers. Non-htmx requests are left to the regular error handling.
      */
     class HtmxErrorToastResolver implements HandlerExceptionResolver {

       private static final Logger LOGGER = LoggerFactory.getLogger(HtmxErrorToastResolver.class);
       private static final String GENERIC_MESSAGE = "An unexpected error occurred.";

       private final HttpStatusMapper httpStatusMapper;
       private final ErrorMessageMapper errorMessageMapper;

       HtmxErrorToastResolver(HttpStatusMapper httpStatusMapper, ErrorMessageMapper errorMessageMapper) {
         this.httpStatusMapper = httpStatusMapper;
         this.errorMessageMapper = errorMessageMapper;
       }

       @Override
       public ModelAndView resolveException(
           HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
         if (!"true".equals(request.getHeader("HX-Request")) || response.isCommitted()) {
           return null;
         }

         // error.handling.http-statuses, @ResponseStatus or the status of a ResponseStatusException
         HttpStatusCode status =
             ex instanceof ErrorResponse errorResponse
                 ? errorResponse.getStatusCode()
                 : httpStatusMapper.getHttpStatus(ex);
         // error.handling.messages, otherwise the exception message for client errors only
         String message =
             errorMessageMapper
                 .getErrorMessageIfConfiguredInProperties(ex)
                 .orElseGet(
                     () -> status.is4xxClientError() ? clientErrorMessage(ex) : GENERIC_MESSAGE);
         if (status.is5xxServerError()) {
           LOGGER.error(
               "htmx request {} {} failed", request.getMethod(), request.getRequestURI(), ex);
         }

         // Shown by <sl:toaster>, which listens for the sl-toast event
         response.setStatus(status.value());
         response.setHeader("HX-Trigger", "{\"sl-toast\":" + Toast.error(message).toJson() + "}");
         response.setHeader("HX-Reswap", "none");
         // An empty ModelAndView marks the exception as handled without rendering a view
         return new ModelAndView();
       }

       private static String clientErrorMessage(Exception ex) {
         if (ex instanceof ErrorResponse errorResponse
             && errorResponse.getBody().getDetail() != null) {
           return errorResponse.getBody().getDetail();
         }
         return ex.getMessage() != null ? ex.getMessage() : GENERIC_MESSAGE;
       }
     }
     ```
  2. Register it right after Spring's `ExceptionHandlerExceptionResolver`, as in option 1a. The starter's
     `@ControllerAdvice` only handles `@RestController` classes, so it never sees the exceptions of your Thymeleaf
     controllers:

     ```java title="HtmxErrorToastConfiguration.java"
     @Configuration(proxyBeanMethods = false)
     class HtmxErrorToastConfiguration implements WebMvcConfigurer {

       private final HttpStatusMapper httpStatusMapper;
       private final ErrorMessageMapper errorMessageMapper;

       HtmxErrorToastConfiguration(
           HttpStatusMapper httpStatusMapper, ErrorMessageMapper errorMessageMapper) {
         this.httpStatusMapper = httpStatusMapper;
         this.errorMessageMapper = errorMessageMapper;
       }

       @Override
       public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
         int index = 0;
         for (int i = 0; i < resolvers.size(); i++) {
           if (resolvers.get(i) instanceof ExceptionHandlerExceptionResolver) {
             index = i + 1;
           }
         }
         resolvers.add(index, new HtmxErrorToastResolver(httpStatusMapper, errorMessageMapper));
       }
     }
     ```
  3. Map your exceptions to a status, either with an annotation:

     ```java title="TeamNotEmptyException.java"
     @ResponseStatus(HttpStatus.CONFLICT)
     public class TeamNotEmptyException extends RuntimeException {

       public TeamNotEmptyException() {
         super("The team still has members and cannot be deleted");
       }
     }
     ```

     or, for exceptions you do not own, in the configuration of the starter (see [REST controllers](#rest-controllers)).

Things to know about this option:

- The exception message of a 4xx error is shown to the user, so keep it free of sensitive information. Use
  `error.handling.messages` to replace the message of library exceptions.
- 5xx errors only show a message that is explicitly configured in `error.handling.messages`.
- Non-htmx requests are left untouched. Spring renders the error page for `@ResponseStatus` and
  `ResponseStatusException`, but does not know the `error.handling.http-statuses` mapping, so other exceptions render
  `5xx.html`.

### Option 2b: Error Handling Starter with translations

The starter's `error.handling.messages` are texts in one language. It does give every exception an error code, the
`code` its JSON responses carry: `TEAM_NOT_EMPTY` for a `TeamNotEmptyException` by default, or what
`@ResponseErrorCode` or `error.handling.codes` sets. Use that code as the message key, `error.<code>`, so the htmx toast
and a client of the REST API know an error by the same name. Start from option 2a, and change it like this:

  1. Give the resolver the starter's `ErrorCodeMapper` and the `MessageSource` as well, and look the message up in
     the locale of the request:

     ```java title="HtmxErrorToastResolver.java"
     /**
      * Shows exceptions of htmx requests as an error toast instead of swapping the error
      * responses. The status is resolved like the Error Handling Spring Boot Starter does for REST
      * controllers; the message is the translation of its error code, if there is one.
      */
     class HtmxErrorToastResolver implements HandlerExceptionResolver {

       private static final Logger LOGGER = LoggerFactory.getLogger(HtmxErrorToastResolver.class);
       private static final String GENERIC_MESSAGE = "An unexpected error occurred.";

       private final HttpStatusMapper httpStatusMapper;
       private final ErrorCodeMapper errorCodeMapper;
       private final ErrorMessageMapper errorMessageMapper;
       private final MessageSource messageSource;

       HtmxErrorToastResolver(
           HttpStatusMapper httpStatusMapper,
           ErrorCodeMapper errorCodeMapper,
           ErrorMessageMapper errorMessageMapper,
           MessageSource messageSource) {
         this.httpStatusMapper = httpStatusMapper;
         this.errorCodeMapper = errorCodeMapper;
         this.errorMessageMapper = errorMessageMapper;
         this.messageSource = messageSource;
       }

       @Override
       public ModelAndView resolveException(
           HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
         if (!"true".equals(request.getHeader("HX-Request")) || response.isCommitted()) {
           return null;
         }

         HttpStatusCode status =
             ex instanceof ErrorResponse errorResponse
                 ? errorResponse.getStatusCode()
                 : httpStatusMapper.getHttpStatus(ex);
         String message = message(ex, status, RequestContextUtils.getLocale(request));
         if (status.is5xxServerError()) {
           LOGGER.error(
               "htmx request {} {} failed", request.getMethod(), request.getRequestURI(), ex);
         }

         response.setStatus(status.value());
         response.setHeader("HX-Trigger", "{\"sl-toast\":" + Toast.error(message).toJson() + "}");
         response.setHeader("HX-Reswap", "none");
         return new ModelAndView();
       }

       private String message(Exception ex, HttpStatusCode status, Locale locale) {
         // An exception with a message key and arguments of its own, as in option 1b
         if (ex instanceof MessageSourceResolvable resolvable) {
           return messageSource.getMessage(resolvable, locale);
         }
         // error.<code>, with the code the REST API returns for this exception
         String translated =
             messageSource.getMessage(
                 "error." + errorCodeMapper.getErrorCode(ex), null, null, locale);
         if (translated != null) {
           return translated;
         }
         // Otherwise as in option 2a, with the generic message translated
         return errorMessageMapper
             .getErrorMessageIfConfiguredInProperties(ex)
             .or(() -> status.is4xxClientError() ? clientErrorMessage(ex) : Optional.empty())
             .orElseGet(
                 () -> messageSource.getMessage("error.unexpected", null, GENERIC_MESSAGE, locale));
       }

       private static Optional<String> clientErrorMessage(Exception ex) {
         if (ex instanceof ErrorResponse errorResponse
             && errorResponse.getBody().getDetail() != null) {
           return Optional.of(errorResponse.getBody().getDetail());
         }
         return Optional.ofNullable(ex.getMessage());
       }
     }
     ```
  2. Pass them in from the configuration class:

     ```java title="HtmxErrorToastConfiguration.java"
     @Configuration(proxyBeanMethods = false)
     class HtmxErrorToastConfiguration implements WebMvcConfigurer {

       private final HttpStatusMapper httpStatusMapper;
       private final ErrorCodeMapper errorCodeMapper;
       private final ErrorMessageMapper errorMessageMapper;
       private final MessageSource messageSource;

       HtmxErrorToastConfiguration(
           HttpStatusMapper httpStatusMapper,
           ErrorCodeMapper errorCodeMapper,
           ErrorMessageMapper errorMessageMapper,
           MessageSource messageSource) {
         this.httpStatusMapper = httpStatusMapper;
         this.errorCodeMapper = errorCodeMapper;
         this.errorMessageMapper = errorMessageMapper;
         this.messageSource = messageSource;
       }

       @Override
       public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
         // find the index as in option 1a
         resolvers.add(
             index,
             new HtmxErrorToastResolver(
                 httpStatusMapper, errorCodeMapper, errorMessageMapper, messageSource));
       }
     }
     ```
  3. Add a message per error code, in every language:

     ```properties title="messages.properties"
     error.unexpected=An unexpected error occurred.
     error.TEAM_NOT_EMPTY=The team still has members and cannot be deleted
     ```

     ```properties title="messages_nl.properties"
     error.unexpected=Er is een onverwachte fout opgetreden.
     error.TEAM_NOT_EMPTY=Het team heeft nog leden en kan niet verwijderd worden
     ```

Things to know about this option:

- A translation wins over `error.handling.messages` and over the exception message, for any status: a key you added is
  a text meant for the user, so it is shown for a `5xx` too.
- The key has no arguments. For a message that needs them ("Team {0} still has members"), let that exception
  implement `MessageSourceResolvable`, as in option 1b; the resolver checks for it first.
- The key follows the starter's error code: with `error.handling.default-error-code-strategy=FULL_QUALIFIED_NAME` it
  is `error.com.example.teams.TeamNotEmptyException`.
- The REST API itself keeps answering with the untranslated `message`; its clients can translate by the `code`.
- See option 1b for the locale and for the error pages' own texts.

### Things to know for all options

- `HX-Reswap: none` leaves the current page untouched, the form and what the user typed included.
- `Toast.toJson()` escapes quotes in the message, and every character outside ASCII, which an HTTP header cannot
  carry. Never build the `HX-Trigger` JSON by concatenating the message yourself.
- A toast with the `error` variant is announced by a screen reader at once. See [Toast](https://shadleaf.dev/1.2.0/components/toast.md#variants).
- Make sure every page that issues htmx requests renders the `<sl:toaster>`. With the toaster in the layout, as the
  [application shell](https://shadleaf.dev/1.2.0/components/application-shell.md) has it, this is automatic.
- With method security (`@PreAuthorize` on a controller), an `AccessDeniedException` passes through the resolver
  before Spring Security sees it. Let Spring Security handle it, so a user who is not signed in is still asked to
  sign in, by returning `null` for it at the start of `resolveException`:

  ```java
  if (ex instanceof AccessDeniedException || ex instanceof AuthenticationException) {
    return null;
  }
  ```

  [htmx after the session expired](https://shadleaf.dev/1.2.0/guides/spring-security.md#htmx-after-the-session-expired) explains how Spring Security
  then answers an htmx request.
- On htmx 2, which does not swap error responses, the resolver works too: it still shows the toast, and
  `HX-Reswap: none` does no harm.

### Testing

Test it with MockMvc by sending the `HX-Request` header. This example uses the `TeamNotEmptyException` of option 1a:

```java
@Test
void failedHtmxDeleteShowsErrorToast() throws Exception {
  doThrow(new TeamNotEmptyException(7L)).when(teams).delete(7L);

  mvc.perform(delete("/teams/7").header("HX-Request", "true"))
      .andExpect(status().isConflict())
      .andExpect(header().string("HX-Reswap", "none"))
      .andExpect(
          header()
              .string(
                  "HX-Trigger",
                  allOf(
                      containsString("\"sl-toast\""),
                      containsString("\"variant\":\"error\""),
                      containsString(
                          "\"title\":\"The team still has members and cannot be deleted\""))))
      .andExpect(content().string(""));
}

@Test
void unexpectedErrorShowsGenericMessage() throws Exception {
  doThrow(new IllegalStateException("could not execute statement; constraint [fk_member_team]"))
      .when(teams)
      .delete(7L);

  mvc.perform(delete("/teams/7").header("HX-Request", "true"))
      .andExpect(status().isInternalServerError())
      .andExpect(header().string("HX-Trigger", containsString("An unexpected error occurred.")))
      .andExpect(header().string("HX-Trigger", not(containsString("fk_member_team"))));
}
```

## REST controllers

If the application also exposes a REST API, use the
[Error Handling Spring Boot Starter](https://github.com/wimdeblauwe/error-handling-spring-boot-starter) to return
consistent JSON error responses (see its
[documentation](https://wimdeblauwe.github.io/error-handling-spring-boot-starter/current/)).

```xml title="pom.xml"
<dependency>
  <groupId>io.github.wimdeblauwe</groupId>
  <artifactId>error-handling-spring-boot-starter</artifactId>
  <version>${error-handling-spring-boot-starter.version}</version>
</dependency>
```

The starter only applies to `@RestController` classes, so it does not interfere with the error pages or the htmx
toasts of your Thymeleaf `@Controller` classes. Its `@ControllerAdvice` is handled by the
`ExceptionHandlerExceptionResolver`, which runs before the htmx resolver above.

Use its configuration to map common exceptions to a proper status and a user-friendly message, for example:

```yaml title="application.yml"
error:
  handling:
    exception-logging: with_stacktrace
    http-statuses:
      org.springframework.dao.DataIntegrityViolationException: conflict
    messages:
      org.springframework.dao.DataIntegrityViolationException: 'The operation conflicts with existing data.'
```
