'Display different error message based on error type

I am fetching data from an api and if response is not ok I wanna throw an error and display its error message.
But, if there is a network error in fetch then I wanna catch it and display a custom error message.

So, I want to display different error message based on error type.

This is how I implemented it.

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 sever. Please try again')
    else
        setError(error.message)

    setPredictionValue(null)
}

Is this ok or is there a better way to do it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source