Add HTMX error handling with toast notifications for 5xx errors
This commit is contained in:
@@ -57,9 +57,41 @@
|
|||||||
{% block content %}{% endblock %}
|
{% block content %}{% endblock %}
|
||||||
|
|
||||||
{% block modal %}{% 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>
|
<script>
|
||||||
|
// 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
|
// Check for global variable to set X-Simulate-500 header
|
||||||
// Set the custom header on all HTMX requests
|
|
||||||
document.addEventListener('htmx:configRequest', function (evt) {
|
document.addEventListener('htmx:configRequest', function (evt) {
|
||||||
if (typeof window.simulate500 === 'boolean' && window.simulate500) {
|
if (typeof window.simulate500 === 'boolean' && window.simulate500) {
|
||||||
evt.detail.headers['X-Simulate-500'] = 'true';
|
evt.detail.headers['X-Simulate-500'] = 'true';
|
||||||
|
|||||||
Reference in New Issue
Block a user