Skip to main content

Handling errors

Two types of errors can occur:

  • Those thrown when rendering a component. To handle this type of error, React recommends implementing Error Boundaries.
  • Standard errors launched by your javascript code (try/catch) or returned by the server.

This step consists in handling this kind of errors.

Final result

The result of this step is as follows:

New in this step

The third product is now named "Invalid product". Clicking on this product simulates an error when the page is rendered.
The "Buy" button now calls an API that returns an HTTP 400 error indicating that the product is not available at the moment

Error boundaries

You can pass a component to <App /> (via the prop ErrorBoundaryComponent). This component will be displayed when an error occurs during the rendering.

First, let's create this component

You can pass a component to <App /> (via the prop ErrorBoundaryComponent). This component will be displayed when an error occurs during the rendering.

First, let's create this component:
getting-started/cra/step07-error-handling/src/modules/core/components/ErrorBoundary.tsx
loading...
tip

This component has access to the application context. It means you can use any Oneki hooks in this component (e.g: useGlobalState)

Update the entry point to pass this component to <App />

getting-started/cra/step07-error-handling/src/index.tsx
loading...

Error handling

When an error occurs (outside the rendering phase), we recommend displaying it via the <NotificationCenter />.
To simulate an error from the server, a new API is exposed by the server that returns an HTTP 400 response with the following body:

{
"message": "The product ${req.body.name} is not available at this moment"
}

Let's update the product details page to:
  • simulate an error during the rendering phase when the product name is "Phone Invalid"
  • display the error from the server via the NotificationCenter.
getting-started/cra/step07-error-handling/src/pages/products/%5BproductId%5D/index.tsx
loading...
tip
<App /> automatically detects any unhandled error and sends a notification on the error topic.
Therefore if you don't specify the onError callback, this notification is sent:
{
topic: 'error',
payload: {
message: ${error.message}
}
...
}

Next step

In the next step, we adapt the application to support different languages (internationalization and localization).