Skip to content

Instantly share code, notes, and snippets.

@tyhopp
Last active May 6, 2024 10:23
Show Gist options
  • Save tyhopp/c009ed7a52a32b794342633c157f8024 to your computer and use it in GitHub Desktop.
Save tyhopp/c009ed7a52a32b794342633c157f8024 to your computer and use it in GitHub Desktop.
renderToPipeableStream error handling
const React = require(`react`);
const { renderToPipeableStream } = require(`react-dom/server`);
const { Writable } = require(`stream`);
function MyComponent() {
throw new Error(`My error`);
}
class MyWritableStream extends Writable {
constructor() {
super();
this._output = ``;
this._deferred = {
promise: null,
resolve: null,
reject: null,
};
this._deferred.promise = new Promise((resolve, reject) => {
this._deferred.resolve = resolve;
this._deferred.reject = reject;
});
}
_write(chunk, _, next) {
this._output += chunk.toString();
next();
}
_destroy(error, next) {
if (error) {
this._deferred.reject(error);
} else {
next();
}
}
end() {
this._deferred.resolve(this._output);
this.destroy();
}
then(resolve, reject) {
return this._deferred.promise.then(resolve, reject);
}
}
async function render() {
const writableStream = new MyWritableStream();
const { pipe } = renderToPipeableStream(React.createElement(MyComponent), {
onAllReady() {
pipe(writableStream);
},
onError(error) {
writableStream.destroy(error);
},
});
try {
await writableStream;
} catch (error) {
console.error(`Caught error with full stack frame`, error);
}
}
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment