forked from nicojs/typed-html
-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
error-boundary.js
42 lines (35 loc) · 1.12 KB
/
error-boundary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const { contentToString } = require('./index');
const { setTimeout } = require('node:timers/promises');
/** @type {import('./error-boundary').ErrorBoundary} */
function ErrorBoundary(props) {
// Joins the content into a string or promise of string
let children = contentToString(props.children);
// Sync children, just render them
if (typeof children === 'string') {
return children;
}
// Adds race condition to children
if (props.timeout) {
children = Promise.race([
children,
setTimeout(props.timeout).then((props.error || HtmlTimeout).reject)
]);
}
// If the error boundary itself throws another error, there's nothing
// we can do, so we just re-throw it.
return children.catch(function errorBoundary(error) {
if (typeof props.catch === 'function') {
return props.catch(error);
}
return props.catch;
});
}
/** @type {import('./error-boundary').HtmlTimeout} */
class HtmlTimeout extends Error {
/** @returns {never} */
static reject() {
throw new HtmlTimeout('Children timed out.');
}
}
exports.ErrorBoundary = ErrorBoundary;
exports.HtmlTimeout = HtmlTimeout;