-
-
Save thiagovsk/a2c0b32ffd444f79bf3bb359521015e1 to your computer and use it in GitHub Desktop.
A developer friendly turboframe error handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Display a developer-friendly error message when Turbo Frame fails to load. | |
if (process.env.NODE_ENV === 'development') { | |
document.addEventListener('turbo:frame-missing', async function (event) { | |
event.preventDefault(); | |
const frame = event.target; | |
const response = event.detail.response; | |
const frameId = frame.id; | |
const url = response?.url || frame.src; | |
const errorDiv = document.createElement('div'); | |
errorDiv.className = 'alert alert-danger'; | |
let detailsEl = ''; | |
if (response) { | |
try { | |
const bodyText = await response.clone().text(); // Clone to preserve original response | |
// Escape script tags in bodyText for safety (optional) | |
const sanitized = bodyText.replace(/<script/gi, '<script'); | |
detailsEl = ` | |
<details style="margin-top: 1em;"> | |
<summary>View response</summary> | |
<iframe srcdoc="${sanitized.replace(/"/g, '"')}" style="width: 100%; height: 400px; border: 1px solid #ccc; margin-top: 0.5em;"></iframe> | |
</details> | |
`; | |
} catch (err) { | |
console.warn('Failed to parse response body:', err); | |
} | |
} | |
errorDiv.innerHTML = ` | |
<strong>Turbo frame error</strong><br> | |
The response does not include <code><turbo-frame id="${frameId}"></code>.<br> | |
${detailsEl} | |
<div style="margin-top: 0.5em;"> | |
${url ? `<a href="${url}" target="_blank" rel="noopener">Open in new tab</a><br>` : ''} | |
</div> | |
`; | |
frame.innerHTML = ''; | |
frame.appendChild(errorDiv); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment