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 |
The three approaches complement each other and can be used together in one application.
Error pages
Section titled “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 errorBest 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.htmland5xx.html, so the user never sees Spring Boot’s “Whitelabel Error Page”. Add dedicated pages for the status codes that need a specific message, typically403and404. - 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).
The examples below assume a layout/main :: layout(pageTitle, content) template that renders the page title as the
h1, as in the application shell and sample-02. Each page puts an
empty state 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:
Thymeleaf source
<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>Rendered HTML
<div class="empty" data-border="dashed"> <div class="empty-header"> <div class="empty-media" data-variant="icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"></path> <path d="M12 17h.01"></path> <path d="M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3"></path> </svg> </div> <div class="empty-title" role="heading" aria-level="2">This page does not exist</div> <div class="empty-description">The address may be mistyped, or the page has moved. Check the address, or start again from the home page.</div> </div> <div class="empty-content"> <a class="button" href="/"> <span class="button-icon" data-icon="inline-start"> <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"></path> <path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path> </svg> </span> Go to the home page </a> </div></div><!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.
<!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:
<!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><!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:
http.authorizeHttpRequests(requests -> requests .dispatcherTypeMatchers(DispatcherType.ERROR).permitAll() // ... your other rules);Technical details
Section titled “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:
spring: web: error: include-message: never include-stacktrace: neverspring: web: error: include-message: always include-exception: true include-stacktrace: alwaysA collapsible in its 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, 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:
<!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:
.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):
Thymeleaf source
<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>Rendered HTML
<div class="empty" data-border="dashed"> <div class="empty-header"> <div class="empty-media" data-variant="icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2"></path> <path d="M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2"></path> <path d="M6 6h.01"></path> <path d="M6 18h.01"></path> <path d="m13 6-4 6h6l-4 6"></path> </svg> </div> <div class="empty-title" role="heading" aria-level="2">Something went wrong on our side</div> <div class="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.</div> </div> <div class="empty-content"> <a class="button" href="/"> <span class="button-icon" data-icon="inline-start"> <svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"></path> <path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path> </svg> </span> Go to the home page </a> </div></div><details class="collapsible error-details" open data-variant="panel"> <summary class="button collapsible-trigger" data-variant="ghost"> Technical details <svg xmlns="http://www.w3.org/2000/svg" class="icon collapsible-trigger-icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="m6 9 6 6 6-6"></path> </svg> </summary> <div class="collapsible-content"> <div class="code-block" x-data="slCodeBlock"> <pre class="code-block-content" tabindex="0"> <code>java.lang.IllegalStateException: Could not reach the mail server at smtp.example.com:587 at com.example.mail.MailService.send(MailService.java:42) at com.example.members.InvitationService.invite(InvitationService.java:31) at com.example.members.MemberController.invite(MemberController.java:58) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:258) ... 48 moreCaused by: java.net.ConnectException: Connection refused at java.base/sun.nio.ch.Net.connect0(Native Method) at java.base/sun.nio.ch.Net.connect(Net.java:589) ... 12 more</code> </pre> <span class="tooltip" x-data="slTooltip"> <button class="button code-block-copy" type="button" data-variant="outline" data-size="icon-sm" hidden aria-label="Copy"> <svg xmlns="http://www.w3.org/2000/svg" class="icon code-block-copy-icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <rect width="14" height="14" x="8" y="8" rx="2" ry="2"></rect> <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon code-block-copied-icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"> <path d="M20 6 9 17l-5-5"></path> </svg> </button> <span class="tooltip-content" role="tooltip" popover="manual" aria-hidden="true"> Copy <span class="tooltip-arrow" aria-hidden="true"></span> </span> </span> <span class="code-block-status sl-sr-only" role="status" data-message="Copied"></span> </div> </div></details>htmx requests
Section titled “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). Instead of handling this in every controller, register one
HandlerExceptionResolver that turns the exception of any htmx request into an error
toast, 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 | Only Thymeleaf pages, one language | An exception that implements UserFacingException |
| 1b: Marker interface with translations | Only Thymeleaf pages, several languages | The same, with a message key instead of a text |
| 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 | 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
Section titled “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.
-
Add the marker interface:
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();} -
Add the resolver:
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.";@Overridepublic 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 statusstatus = 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 pagetry {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 eventresponse.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 viewreturn new ModelAndView();}} -
Register it right after Spring’s
ExceptionHandlerExceptionResolver. That way your own@ExceptionHandlermethods and@ControllerAdviceclasses still take precedence, but the resolver runs beforeResponseStatusExceptionResolverandDefaultHandlerExceptionResolverturn the exception into an error page:HtmxErrorToastConfiguration.java @Configuration(proxyBeanMethods = false)class HtmxErrorToastConfiguration implements WebMvcConfigurer {@Overridepublic 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());}} -
Implement the marker on your own exceptions:
TeamNotEmptyException.java public class TeamNotEmptyException extends RuntimeException implements UserFacingException {public TeamNotEmptyException(long teamId) {super("Team " + teamId + " is still referenced by members");}@Overridepublic HttpStatusCode getStatusCode() {return HttpStatus.CONFLICT;}@Overridepublic 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@ResponseStatusgets a500. - The resolver also sets the status of a
UserFacingExceptionfor full page requests, so Spring Boot renders the matching error page (4xx.htmlfor a409) instead of5xx.html.
Option 1b: marker interface with translations
Section titled “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:
-
Make the marker extend
MessageSourceResolvableinstead of declaringgetUserMessage():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();} -
Give the resolver the
MessageSource, and resolve both messages in the locale of the request:HtmxErrorToastResolver.java class HtmxErrorToastResolver implements HandlerExceptionResolver {// LOGGER and GENERIC_MESSAGE as in option 1aprivate final MessageSource messageSource;HtmxErrorToastResolver(MessageSource messageSource) {this.messageSource = messageSource;}@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {// the htmx check as in option 1aLocale 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}} -
Pass it in from the configuration class, which can inject it:
HtmxErrorToastConfiguration.java @Configuration(proxyBeanMethods = false)class HtmxErrorToastConfiguration implements WebMvcConfigurer {private final MessageSource messageSource;HtmxErrorToastConfiguration(MessageSource messageSource) {this.messageSource = messageSource;}@Overridepublic void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {// find the index as in option 1aresolvers.add(index, new HtmxErrorToastResolver(messageSource));}} -
Let your exceptions give the key, its arguments, and the text to show when no language has the key:
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;}@Overridepublic HttpStatusCode getStatusCode() {return HttpStatus.CONFLICT;}@Overridepublic String[] getCodes() {return new String[] {"error.team-not-empty"};}@Overridepublic Object[] getArguments() {return new Object[] {teamName};}@Overridepublic String getDefaultMessage() {return "The team still has members and cannot be deleted";}} -
Add the messages, in every language:
messages.properties error.unexpected=An unexpected error occurred.# {0}: the name of the teamerror.team-not-empty=Team {0} still has members and cannot be deletedmessages_nl.properties error.unexpected=Er is een onverwachte fout opgetreden.# {0}: the name of the teamerror.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’sLocaleResolver, so the toast follows the same language as the page: the browser’sAccept-Languageby default, or the language the user picked.- The message is a
MessageFormatpattern 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 guide covers Shadleaf’s own texts, which the toaster’s close button uses.
Option 2a: Error Handling Starter
Section titled “Option 2a: Error Handling Starter”If the application already uses the Error Handling Spring Boot Starter 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 |
-
Add the resolver:
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;}@Overridepublic 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 ResponseStatusExceptionHttpStatusCode status =ex instanceof ErrorResponse errorResponse? errorResponse.getStatusCode(): httpStatusMapper.getHttpStatus(ex);// error.handling.messages, otherwise the exception message for client errors onlyString 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 eventresponse.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 viewreturn 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;}} -
Register it right after Spring’s
ExceptionHandlerExceptionResolver, as in option 1a. The starter’s@ControllerAdviceonly handles@RestControllerclasses, so it never sees the exceptions of your Thymeleaf controllers: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;}@Overridepublic 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));}} -
Map your exceptions to a status, either with an annotation:
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).
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.messagesto 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
@ResponseStatusandResponseStatusException, but does not know theerror.handling.http-statusesmapping, so other exceptions render5xx.html.
Option 2b: Error Handling Starter with translations
Section titled “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:
-
Give the resolver the starter’s
ErrorCodeMapperand theMessageSourceas well, and look the message up in the locale of the request: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;}@Overridepublic 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 1bif (ex instanceof MessageSourceResolvable resolvable) {return messageSource.getMessage(resolvable, locale);}// error.<code>, with the code the REST API returns for this exceptionString translated =messageSource.getMessage("error." + errorCodeMapper.getErrorCode(ex), null, null, locale);if (translated != null) {return translated;}// Otherwise as in option 2a, with the generic message translatedreturn 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());}} -
Pass them in from the configuration class:
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;}@Overridepublic void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {// find the index as in option 1aresolvers.add(index,new HtmxErrorToastResolver(httpStatusMapper, errorCodeMapper, errorMessageMapper, messageSource));}} -
Add a message per error code, in every language:
messages.properties error.unexpected=An unexpected error occurred.error.TEAM_NOT_EMPTY=The team still has members and cannot be deletedmessages_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.messagesand over the exception message, for any status: a key you added is a text meant for the user, so it is shown for a5xxtoo. - 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_NAMEit iserror.com.example.teams.TeamNotEmptyException. - The REST API itself keeps answering with the untranslated
message; its clients can translate by thecode. - See option 1b for the locale and for the error pages’ own texts.
Things to know for all options
Section titled “Things to know for all options”-
HX-Reswap: noneleaves 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 theHX-TriggerJSON by concatenating the message yourself. -
A toast with the
errorvariant is announced by a screen reader at once. See Toast. -
Make sure every page that issues htmx requests renders the
<sl:toaster>. With the toaster in the layout, as the application shell has it, this is automatic. -
With method security (
@PreAuthorizeon a controller), anAccessDeniedExceptionpasses 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 returningnullfor it at the start ofresolveException:if (ex instanceof AccessDeniedException || ex instanceof AuthenticationException) {return null;}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: nonedoes no harm.
Testing
Section titled “Testing”Test it with MockMvc by sending the HX-Request header. This example uses the TeamNotEmptyException of option 1a:
@Testvoid 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(""));}
@Testvoid 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
Section titled “REST controllers”If the application also exposes a REST API, use the Error Handling Spring Boot Starter to return consistent JSON error responses (see its documentation).
<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:
error: handling: exception-logging: with_stacktrace http-statuses: org.springframework.dao.DataIntegrityViolationException: conflict messages: org.springframework.dao.DataIntegrityViolationException: 'The operation conflicts with existing data.'