History, errors, and enhancement

Handle HTTP errors

Show useful server failure or validation markup while keeping the affected controls recoverable.

8 minute lesson

~~~

An HTTP error means the server responded, but the result was not successful. HTMX triggers htmx:responseError, and it does not swap the body by default.

Treat expected validation differently from an unexpected server failure. A 422 response can contain a form designed for display, so allow it deliberately:

document.addEventListener("htmx:beforeSwap", event => {
  const status = event.detail.xhr.status

  if (status === 422) {
    event.detail.shouldSwap = true
    event.detail.isError = false
  }
})

The server can use HX-Retarget to send that form to a stable region. A 500 should instead produce a generic message and retry path; never swap a framework error page or stack trace into the application.

Keep the status accurate for monitoring and debugging. Handle 401, 403, 404, 409, 422, and 500 according to their meaning rather than collapsing every problem into 200.

Force each relevant response in development. Verify the final DOM, focus, enabled controls, visible message, and Network status—not only that an event fired.

Lesson completed