Open In App

How to simplify an error callback in ReactJS ?

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article discusses simplifying error callbacks in React, focusing on handling errors during actions like HTTP requests or JSON data interpretation. While default behavior logs errors in the console, the article advocates for improved user experience by implementing error handling to display user-friendly messages and prevent confusion in the application.

Prerequisites:

Steps to Create the React Application And Installing Module:

Step 1: Create a react application using the following command.

npx create-react-app my-app

Step 2: Change your directory to the newly created folder by using the following command.

cd my-app

Project Structure:

Project Structure

The updated dependencies in package.json file will look like :

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Approach 1: Without Simplifying error callback

Here is an example of a component that makes an error and just has a button and the error is logged in the console. Let’s assume that our code fails here by clicking the “Simulate Error” button.

Example: This example illustrates the above-mentioned approach

Javascript




import React, { useState } from 'react';
 
function ErrorHandlingExample() {
    const [error, setError] = useState(null);
 
    const handleClick = async () => {
        console.log(error.message);
    };
 
    return (
        <div>
            <button onClick={handleClick}>
                Simulate Error
            </button>
        </div>
    );
}
 
export default ErrorHandlingExample;


Step to Run the Application: Open the terminal and type the following command.

npm start

Output:

Output

Approach 2: Using async-await

Utilizing async-await syntax in React simplifies error callback management for asynchronous operations, enabling synchronous-like code readability and debugging. By encapsulating asynchronous tasks in a try-catch block, errors can be caught and handled efficiently. This approach enhances code clarity, readability, and streamlines the error handling process in React applications.

Syntax:

const handler_name = async () => {
try {
//... await
} catch (e) {
//...
}
};

Example: This example illustrates the above-mentioned approach

Javascript




import React, { useState } from 'react';
 
function ErrorHandlingExample() {
    const [error, setError] = useState(null);
 
    const delay = async (ms) => {
        return new Promise(resolve => setTimeout(resolve, ms));
    };
 
    const handleClick = async () => {
        try {
            await delay(2000);
            setError("Something went wrong!");
        } catch (e) {
            console.error(e);
        }
    };
 
    return (
        <div>
            <button onClick={async () => await handleClick()}>
                Simulate Error
            </button>
            {error && <p style={{ color: "red" }}>{error}</p>}
        </div>
    );
}
 
export default ErrorHandlingExample;


Step to Run the Application: Open the terminal and type the following command.

npm start

Output:

Output

Example 2: Using Promise

Let’s see a working example of an error callback using async-await syntax.  Instead of making a network request, we will just use a simple setTimeout function to represent an asynchronous operation that could fail. A simple button is used for rendering errors.

Syntax:

let promise = new Promise(function(resolve, reject){
//do something
});

Javascript




import React, { useState } from 'react';
 
function ErrorHandlingExample() {
    const [error, setError] = useState(null);
 
    const handleClick = async () => {
        try {
            await new Promise(
                resolve => setTimeout(resolve, 2000));
            setError("Something went wrong!");
        } catch (e) {
            console.error(e);
        }
    };
 
    return (
        <div>
            <button onClick={handleClick}>
                Simulate Error
            </button>
            {error && <p style={{ color: "red" }}>{error}</p>}
        </div>
    );
}
 
export default ErrorHandlingExample;


Step to Run the Application: Open the terminal and type the following command.

npm start

Output:

Output



Similar Reads

What is the difference between returning a callback and just calling a callback ?
In programming, a callback function is a function that is passed as an argument to another function, which executes the callback function whenever it requires to do so to complete a certain task. Callback function provides a variety of powerful programming techniques. Callback function makes function execution much more dynamic by allowing what kin
3 min read
What to understand Callback and Callback hell in JavaScript ?
JavaScript, a single-threaded language, relies on callbacks for handling asynchronous tasks. Callbacks execute code once an operation finishes. But as the code complexity increases, the risk of callback hell emerges. Callback: A callback is a function that is passed as an argument to another function that executes the callback based on the result.
2 min read
Error-First Callback in Node.js
Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument.The second argument of the callback functio
2 min read
What is an error-first callback in Node.js ?
In this article, we are going to explore the Error-first callback in Node.js and its uses. Error-first callback in Node.js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This error object is returned by the first argument whene
2 min read
Which is preferred option with in callback refs and findDOMNode() in ReactJS ?
ReactJS employs two prominent concepts, namely callback refs and `findDOMNode()`, for effective DOM manipulation. These mechanisms facilitate access to DOM elements, enabling the implementation of diverse changes such as hiding or showing elements, altering styles, and focusing on specific elements. Table of Content findDOMNode()Callback refsPrereq
4 min read
How to retrieve error message using Exception class in PHP when error occurred ?
Exception handling is the important part of PHP in which we deal with how to maintain the flow of the program if there is an error or exception that occurs during the compilation. As you know we can handle the exception by throw, try-catch, die method so now we understand how to retrieve the error message using exception class by given below exampl
2 min read
Difference between throw Error('msg') and throw new Error('msg')
The throw statement allows you to create an exception or a custom error. The exception can be like a Javascript string, a number, a boolean, or an object. So, If you use this statement together with the try...catch statement. It allows you to control the flow of the program and generate accurate error messages. For example: throw "too small" (throw
3 min read
Express Returns Servers HTML Error Page Instead of res.json Error Message
ExpressJS is a backend web application framework built on top of NodeJS which helps us manage the server and routing. It has some powerful functionalities like middleware, templates, and debugging which help us to write efficient and faster code. It helps us extensively in building web applications. In this article, we will see why "Express returns
3 min read
Difference between Type Error and Reference Error in JavaScript
JavaScript is one of the most popular programming languages in the world, and it is used by millions of developers to create dynamic and interactive web applications. However, like any programming language, JavaScript is not without its quirks and pitfalls. Two common issues that developers often encounter when working with JavaScript are Type Erro
6 min read
Error Handling with Error Boundary Hooks
In the world of web development handling errors effectively is crucial for providing a seamless user experience. React one of the most popular JavaScript libraries provides a powerful feature known as Error Boundary Hooks that allows developers to handle errors in their applications. In this article, we will explore how Error Boundary Hooks can be
2 min read