Intro

This is a practice guide how to handle in React’s error situations, using error boundary component.
It’s contain a quick how-to guide to this React feature, and some common-mistakes that I’ve encountered by the development process.
Who’s want to dig deeper in the material can see the official doc.

Content:

Live Example

If you are eager to see things on action – see this example (which anyway will be discussed on the next)

EXAMPLE 

About error – handling + see it’s on action

Sometime the things getting into error and we should know how to handle it.

For example I have component on my app that if the data arrived from the server is corrupted, although it's only one of many good items, all the app fall down.

When Your app has crushed

via GIPHY

Important tip – when the screen out to error view and you want to return to the last viewed screen press ESC (you also have an x also to close the error. Sometimes, it's just layout for development mode, as will explained next ).

So let's inspect that.

Simple error

So for inspect a problem I love to make a basic example, like POC – to see the problem.

See this example with NOT working component (you can open it in other window with code editor – for your convenient) :

Tip:  You can play with the valid/inValid data at this line of code – for switch from not-working to working state.

change 

<ContainerWithoutHandle arr = {inValidData}/>

To

<ContainerWithoutHandle arr = {validData}/>

This is simple list that shows elements which each get array of two elements and show them.. If you pass undefined array  or null it will generate error.

So, how to handle it? How would I make that even though one of the components is broken the app’s UI won’t be crashed?

Error Boundaries

After quick search you can found that error-boundaries functionality of React.

Official Live demo

You can read about that, and see the following live demo of the official docs, it’s pretty simple. Anyway I will write a quick brief of using of that.

I won’t go very deep and cover all the aspects, you can see it on the docs. I prefer to write down some important and useful point that I have encountered.

Error boundaries is saying to create a general component, by using two functions (componentDidCatch() , getDerivedStateFromError(error) ) to recognize the error, and then you can define the look of the rendering you want will happen when the error is happening. You can also to define nothing if that’s what you want.

Live Examples

If you eager to see it on action you can look in those 2 examples :

1- Component with error :

As mentioned above – You can play with the valid/inValid data at this line of code – for switch from not-working to working state.

2- Component that handling the error:

There is some more important example at this page that I’ll explain later

It’s the same container as  the above example – but with handling, see how the error catched, and the UI I defined for the broken component is shown. Other components on the list , are shown well.

What’s going on under the hoods and how to do it?

What’s happen is that I have created general component, which define two major functions :

    static getDerivedStateFromError & componentDidCatch

Those 2 functions are triggered when error occur on the running. Also, I did a conditionally render – in regular state – it will render the child component. In error state – it will render other view. Also, I defined state props that will be used as indicator to error state.

Inside the mentioned functions – I defined a change to the state props , so they will change them when they called.

From now on all I have to do is to wrap the element that I want that will caught and if it or one of it’s children will through an error, the error-handling-view will be shown.

For example :

const var1 = useMyCusom();

*Tip – when we saying “children” in React context this mean a component that stand inside tags of other (parent component) :

<ParentComp><ChildComp/></ParentComp>

It doesn’t mean – extended class (which in anycase depcrated on React), or component inside the render function, Or any other case. Remember that.

Feel a little confused ? Please see again the above live examples and play with them, and I’m sure that you will understand.

So after we understand the idea we can now list down the todo list :

Steps to define error boundaries :

  • Create a general component
  • Create to that a state with some error identification properties
  • Add to it the static getDerivedStateFromError(error) – and define there what will happen to the state when this function will be called. The function called when error occurred. (it’s recommended for the UI changes)
  • You can add also componentDidCatch errorm which contain also data about the error and recommended for side – effects things. This mean, other outer function that should happen because that error. (in the next I will touch a little about the different between those two above functions).
  • Define conditional render, that in regular state – return the child, and if the state identifier is error return your desire UI.

That’s in basic talk, about error-boundaries. Here I’ll write down some more important points that I think it’s good to know. If you feel like you know enough and you encounter problems you can skip to the section of common mistakes. But I think that basic understand of this points can save you problems.

So now we can start play with that. But there are more basics that should be noticed. I will pass on them according to the common mistakes.

Error Boundaries NOT WORKING – WHY ???

Don't be frustrated

via GIPHY

So it’s always a challenged (Painful and enjoyable ) step on programming. You try something and it doesn’t work. I know, it’s sometime frustrated to programming. Each programmer know – it’s part of the game. But you don’t need to be frustrated – follow the instructions below and I hope everything will be alright.

Let’s check the possible reasons.

First, I will list them down, then I will explain them in details:

Common mistakes :

Solution to common mistakes (and things that important to know )

It's working but you think it isn’t (hidden by the overlays)

Sometimes at development environment (when you launch it by npm start) the error does caught by the error boundaries, but you get the screen of the error stacks. Like in the below picture . In such case, you just need to click the ‘X’ button or ESC. Then you can see the screen again and if the error didn’t caught.

It’s defined like that since the error is doesn’t wanted case, and they want to encourage the developer and remind him that he should fix it. On production mode – it won’t happen.

I didn’t figure out in which scenario this symptom happens since it’s not always drop to this screen. 

This is a SO question about that : https://stackoverflow.com/questions/52096804/react-still-showing-errors-after-catching-with-errorboundary

Anyway if you want to see it on production you can just compile and run it on production (it’s also an important thing for React developer to know – run the app in production). See here details on how to run in production –

 https://create-react-app.dev/docs/deployment/  Or if you fun of SO : https://stackoverflow.com/a/49209041/9727918

(notice that you need to serve it from the project folder, from where you run npm start, also if you use proxies – on production proxies don’t working ). – https://stackoverflow.com/questions/52877492/proxy-not-working-for-create-react-app-in-production/52881317#52881317

You forgot to implement the functions with the states. / You forgot to make the condition at the render

Well those steps are explained at the “Steps to define error boundaries “ above. If you miss one of the steps, it won’t work properly.

You are wrapping whole list, instead of wrapping each element (inside the loop/map)

Error boundaries will work directly on local children. Not on sub-child.

This mean that if in the sub-child will occur a problem but only the parent this is wrapped, it will catch all the parent .

For example if I wrapped a component that contain list of items and one of the item throw error, all the list will be caught. If I want that only the item will be caught I need to wrap each item inside the I need to wrap each item when I generates the list. (Or I can wrap them both and the close error will be caught)

See at the working example the “Container WITH parent Handle”.  Compare it to the first “Container WITH Handle for each item” component.

The same rule is right about inner handling when you define the error-handling on the parent component. See at the example the title : “Container WITH inner defined Handle”.

You Define the handling inside the problematic component

Continue to above – if you do an inner handling inside the problematic component, it won’t be caught. It’s need to be caught by a parent.

See at the example the title “ Problem in ContainerWithInnerHandle “.

You are trying to handle event-error

Handling events handlers errors (Event Handlers)

As explained here –  

Error boundaries do not catch errors inside event handlers.

React doesn’t need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering. So if they throw, React still knows what to display on the screen

See at the live example the section “Handling events handlers errors” for this on action.

References

The React official doc on error-boundaries –

https://reactjs.org/docs/error-boundaries.html

Conclusion

Error – Boundaries is efficient way to catch unexpected UI errors in React. With using that you can ensure that if component’s error will happen the whole UI won’t crash.

You need to know some notes regarding that for implement this well.

***About The Author***

Hope this article was useful for you. Feel free to write reply for any feedback you want, share it, and do like.

Thanks for reading.

I am Izhar Mashkif, a full-stack WEB developer from Israel.

If you need consulting, development or any other issue feel free to contact me :

yimprogramming@gmail.com, Linkedin, 054-7477637 .

I am looking for interesting projects where I can push the project forward and get the things done and the idea become reality.

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *