Add HTMX error handling with toast notifications for 5xx errors

This commit is contained in:
Bryce
2025-08-12 07:24:56 -07:00
parent c159393809
commit 93b5bc091c

View File

@@ -57,14 +57,46 @@
{% block content %}{% endblock %}
{% block modal %}{% endblock %}
</script>
<!-- Toast for 5xx errors -->
<div id="error-toast" class="toast toast-top toast-end hidden">
<div class="alert alert-error">
<span id="error-message"></span>
<button class="btn btn-sm btn-ghost" onclick="document.getElementById('error-toast').classList.add('hidden')">Close</button>
</div>
</div>
<script>
// Check for global variable to set X-Simulate-500 header
// Set the custom header on all HTMX requests
document.addEventListener('htmx:configRequest', function (evt) {
if (typeof window.simulate500 === 'boolean' && window.simulate500) {
evt.detail.headers['X-Simulate-500'] = 'true';
// Configure HTMX to handle 5xx errors
document.addEventListener('htmx:responseError', function(evt) {
if (evt.detail.xhr.status >= 500 && evt.detail.xhr.status < 600) {
const toast = document.getElementById('error-toast');
const message = document.getElementById('error-message');
// Extract error message from response
let errorMessage = 'Server Error';
try {
const responseJson = JSON.parse(evt.detail.xhr.response);
if (responseJson.error) {
errorMessage = responseJson.error;
}
} catch (e) {
// If not JSON, use the raw response
errorMessage = evt.detail.xhr.response || 'Server Error';
}
});
message.textContent = errorMessage;
toast.classList.remove('hidden');
}
});
// Check for global variable to set X-Simulate-500 header
document.addEventListener('htmx:configRequest', function (evt) {
if (typeof window.simulate500 === 'boolean' && window.simulate500) {
evt.detail.headers['X-Simulate-500'] = 'true';
}
});
</script>
</body>
</html>