AHA demos
← All demos

Error handling

Five buttons, five kinds of response. Where each one lands on the page is decided by its status code.

#result
#validation
#server

Events

  • None yet. Click 404, 500 or Timeout.

What to look at

htmx 4 swaps every response, whatever the status. That is what makes server-side validation easy: a 422 with the form re-rendered is just a normal swap. But you don't always want errors in the same place as results.

hx-status handles that per status code. hx-status:422="target:#validation" sends validation errors to one box. hx-status:5xx="target:#server" matches any 500-range code. hx-status:404="swap:none" ignores the body entirely. The default, the 200, goes to hx-target.

Anything 400 or above also fires htmx:response:error. Alpine listens for it on the wrapper (events bubble) and writes it to the log. The event's detail.ctx carries the request context, including the Response. A network failure or a timeout fires htmx:error instead, since there was no response at all.

The Timeout button uses hx-config="timeout:1500ms" against an endpoint that takes 4 seconds. htmx aborts the fetch. Nothing is swapped.

Source

Loading source…

Every file of this demo, as it runs. Or browse it on GitHub ↗