Babel plugin to wrap render() method in React.Component with try-catch statement.
React 16 has error handling but for client rendering only.
This plugin performs simple transform which wraps event render() method with try-catch. Example:
// MyComponent.js
class MyCompoenent extends React.PureComponent {
render() {
return <div/>;
}
}
This component will be transofmed to:
// MyComponent.js
const ReactSSRErrorHandler = require('./path/to/my/SSRErrorHandler.js');
class MyCompoenent extends React.PureComponent {
render() {
try {
return this.__originalRenderMethod__();
} catch (e) {
return ReactSSRErrorHandler(e, this.constructor.name);
}
}
__originalRenderMethod__() {
return <div />;
}
}
Actually, this is temporary solution until React doesn't support error handling in SSR.
npm install --save-dev @doochik/babel-plugin-transform-react-ssr-try-catch
You should enable this plugin only for server build. Use React 16 error boundaries from cient build.
.babelrc
{
"plugins": [
["react-ssr-try-catch", {
"errorHandler": "./path/to/my/SSRErrorHandler.js"
}]
]
}
Path to your errorHandler module.
This is simple function with two arguments (error, componentName)
// SSRErrorHandler.js
module.exports = (error, componentName) => {
// here you can log error and return fallback component or null.
}