Show various error messages depending on the type of error detected

When pulling data from an API, my goal is to handle errors appropriately by displaying custom error messages based on the type of error that occurs. If the response is not okay, I want to throw an error and show its message. However, if there is a network error during the fetch process, I want to catch it and display a different customized error message.

This is how I have set up the error handling:

try {
    const res = await fetch(`http://localhost:8000/api/prediction/${model.ticker}/?` + new URLSearchParams({
        pred_date: predictionDate,
    }))

    if (!res.ok)
        throw Error('Invalid date')

    const predictionValue = await res.json()
    setPredictionValue(predictionValue)
} catch (error) {
    if (error.name === 'TypeError')
        setError('Failed to fetch data from server. Please try again.')
    else
        setError(error.message)

    setPredictionValue(null)
}

Does this implementation work as intended, or is there a better approach to handle these error scenarios?

Answer №1

Although your code is mostly correct, I suggest a few improvements:

  • Make sure to always utilize the new keyword when creating instances of errors: throw new Error('whatever')

  • Replace error.name === 'TypeError' with error instanceof TypeError.

Why? The concept of "Duck typing" involves observing an object's properties to determine its type. While Duck typing can work most of the time, it is not the ideal approach. It is recommended to explicitly check if the object matches the desired type, which is more precise in this scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing the performance of your code by optimizing it using jQuery when a checkbox is either checked or

Looking for ways to optimize a jquery function that toggles a URL parameter based on checkbox status. Any suggestions on how to streamline this code? $('#mapControl').live('click', function(){ var thisUrl = $(location).attr(' ...

Encountered an uncaughtException in Node.js and mongoDB: User model cannot be overwritten once compiled

Currently, I am utilizing this import statement const User = require("./Usermodel")' However, I would like to modify it to const User = require("./UserModel") Despite my efforts to align the spelling of the import with my other i ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

The Node.js execSync functionality is not functioning as expected, as the changes made to the system are not taking effect

I'm looking to prevent chrome.exe from accessing the internet through the Windows firewall. The specific command I need to use is netsh advfirewall firewall add rule name="Block Chrome" dir=out action=block program="C:\Program Files (x86)\G ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Transmit a document to the OpenAI API without the need to interact with the file storage system

Is there a way to send file data to the OpenAI API without directly accessing the file system? I have the file contents stored as a string and would like to bypass reading from the file system. The code provided in the OpenAI documentation involves reading ...

The Mongoose .lt method is unable to process the post value

I came across this interesting Mongoose function snippet: exports.readSign = function(req, res) { if (req.user.roles.indexOf('admin') === 1) { Timesheet.find() .where('projectId').equals(req.params.projectId) ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

My attempt at utilizing the regex function was unsuccessful

When attempting to use a regex function for matching tags in the title and caption, it appears to work fine. However, adding more matching tags causes the function to fail. Below is the code snippet that functions correctly without any issues: $(".si ...

Avoiding the insertion of styles into the HEAD section when using Webpack MiniCssExtractPlugin in combination with Create React

Currently, I am utilizing create-react-app to develop a component library with Storybook JS. The ultimate goal is to release an NPM package containing these components for use in various projects. Within this library, SASS is employed, complete with global ...

Sort through data based on specific data fields upon the button click event using JSON and Vue.js

Is there a way to use JSON files in Vue.js to filter data based on category when a button is pressed? I have objects with categories inside the data. portfolio-v1.json { "data":[ { "image_path":"static/products/DEL ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...

Allow users to interact with table rows by making them clickable and sending a post parameter to a jQuery

After creating a table and populating it with elements using JSTL tags and EL expressions, the next step is to make each row clickable. This can be achieved by implementing the following function: $("tr").click(function() { window.location.href = $(th ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Error Message: A key is being provided to the classes property that is not implemented in the current context

Trying to customize Material-UI styles with makeStyles() as outlined in the documentation but encountering a warning when passing a classname in the parent component that is not specified in useStyles. The warning message reads: Warning: Material-UI: th ...

An async function cannot be used as a Constructor

I am in the process of creating a constructor function using JavaScript. This constructor needs to be asynchronous because I am utilizing the Phantom JS module for data scraping. As a result, an asynchronous function must be used to scrape data through Pha ...