React JS with Error Boundary Features
Error Boundary is a new feature for React 16. This feature is introduced for handling the UI fallback error.In React 15 or earlier version, there is no feature to handle the UI fallback directly, just using try..catch to handle error.
If error occured, whole application will crash and browser shows white blank window or screen. Error Boundary is added to react component render life cycle and it will catch error and generate error information, so we can use it to build error reporting service for our application.
Error boundaries do not catch errors for Event handlers, Asynchronous code (e.g. setTimeout
or requestAnimationFrame
callbacks), Server side rendering and Errors thrown in the error boundary itself.
How Error Boundary works in react component life cycle
In react,a class component becomes a error bounday, if developer use those two method named static getDerivedStateFromError()
or componentDidCatch()
. Also developer can use both function together to implement error bounday in react component.
static getDerivedStateFromError()
use for handle the UI fallback after error has been thrown.componentDidCatch()
can use for log or render theerror
information.
Or developer can only use componentDidCatch()
method to handle the UI fallback and log or create error reporting for application.
Implement Simple Error Boundary in React Component
- Install the
create-react-app
npm package, if this package is not available locally in you computer.
> npm install -g create-react-app
2. Create the project named react-error-handling
from command line and go to that folder.
> create-react-app react-error-handling
> cd react-error-handling
3. Create folder name components
in src
folder in react-error-handling
application.
4. Create the file in src/components/Home.js
, which is contains the sample code for error handling
In line 3...10, I add the constructor and call the super(props), which will give access to use state for react component.hasError: This state will use for handle error block in render function, to make change hasError state value to true in getDerivedStateFromError() function in line 12...14 which will execute after execption occured. which is then use in render()
function to check error in line 21...23.In line 16...19,
componentDidCatch(error, info) function, which return error and info during error or execption happen.we can also change the state of hasError in this function.(e.g: this.setState({
hasError: true
});
so we do not need to use getDerivedStateFormError()
function to change hasError state.Error Boundary works with chield component. those two function should be declare in HOC (Higher Order Component)In line 40...44, for testing purpose,I added the chield component named <TestElement/>, which is then use for testing Error bounday in <Home /> component. In line 42, using the function named toString() with props.name attribute. which is then create execptions if props.name is undefined.
5. Copy and Past below code in App.js
in pathsrc/App.js
of your application
In line 2, Import the Home component to App componentThen In line 9, Add the Home Component to App component as chield.
6. Then Go to terminal
or cmd
and run this command below
> npm start
Actually
create-react-app
has built in error reporting. Indevelopment
stage, error boundary and error reporting both are appared in runtime. But in production build, It shows only error bounday if any error occured.
After running command, In react-creact-app
overlap the error-bounday
output with it’s own error reporting layout.
Click on Cross button remove create-react-app
default reporting layout. shows actual output of Error Boundary
in figure below.
If you are using only react js without using
create-react-app
npm package or there is a boilerplate with no error reporting tools . You can get the last output directly when run the commandnpm start
.
If you want to see only error reporing, you need to create Production Build for create-react-app
, which will automatically remove error reporting layout from applicaiton, shows only Error Bounday
.
- First you have to install the
serve
npm package, for runing the production build ouput to browser.
> npm install -g serve
2. Then build the production build by npm or yarn
> npm run buildor > yarn build
3. To show the production build to browser run this command below
> server -s build
Open browser past the link, you will see the error boundary on you application in browser.
Create Error Bounday Higher Order Component (HOC)
2. Create ErrorBoundary file to src/components/ErrorBoundary.js
(HOC) Higher Order Component
In line 7...9, I have added the state named hasError , which will then use in line 12...14 function named getDerivedStateFromError()to change the state when error occured in chield element.In line 16...23,I can also change hasError state here. No need to use getDerivedStateFromError() if we change state from in componentDidCatch() function.You can also send the error information to your custom error reporting service application. to solve the error in production.In line 25...50, add the custom react component, which is then render to applicaiton, when error occured in any chield component.In line 37...43, I have added the image for error bounday to beautify the error component.In line 50...52,I have added the this.props.children. which will return all the react elements or objects or properties between <ErrorBounday> start tag to end tag.For example, if any developer want to create the Header for any application. developer may use this.props.children to solve this problem. this children property helps to wrap any component within it named Higher Order Component(HOC).
Sample Data for Testing the Error Bounday
- Create JSON file named
user.json
atsrc/components
folder. you can download the file from this link . In that file you can get json array or user, which screen shot is provided below.
In Json array, there is object which has no website
attribute. it can create any types of javascript error during render time.
So we need to create Error boundary for user list.
which can shows broken info error message in production without provide any UI fallback information.
Applying The Error Bounday Component To React JS Component
Now we can create the UserList
component, which contains User
component and Add Error Bounday
, which is then handled the error in production and provide custom error message by <ErrorBoundary />
HOC component.
In line 2,I have import user.json file to get the array of user to render in <UserList /> component using <User /> component.In line 3, I have import <ErrorBoundary /> component to wrap the error or execption of <UserList /> component.In line 5...28, I have added the <User /> Component which will show the user information from json file.In line 24, I use toString() function to the website field in User Object. If website field is not available at user object, this function create execption. Without using Error Boundary, whole app will crash and show white blank page.In line 35...41, I add the iteration to User Array which is saved in user.json file.In line 37...39, I wrap the <User /> component with <ErrorBounday /> component. If any error happend in <User /> component, that error will handled by <ErrorBoundary /> HOC component. show the formated error which is designed for.
Ourput of the Custome Error Bounday Example Code
You can find the All the code from Github link