Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thiagovsk/a2c0b32ffd444f79bf3bb359521015e1 to your computer and use it in GitHub Desktop.
Save thiagovsk/a2c0b32ffd444f79bf3bb359521015e1 to your computer and use it in GitHub Desktop.
A developer friendly turboframe error handler
// 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, '&lt;script');
detailsEl = `
<details style="margin-top: 1em;">
<summary>View response</summary>
<iframe srcdoc="${sanitized.replace(/"/g, '&quot;')}" 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>&lt;turbo-frame id="${frameId}"&gt;</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