Reputation: 452
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?
Upvotes: 0
Views: 511
Reputation: 9127
What you have is mostly fine, but I'd recommend a couple of tweaks:
always use the new
keyword when creating instances of errors: throw new Error('whatever')
change error.name === 'TypeError'
to error instanceof TypeError
.
Why? "Duck typing" is what we call studying the properties on an object to figure out what kind of thing it is. Duck typing usually gives you the right answers, but it shouldn't be your first choice. It's better to directly ask if the thing is the kind of thing you care about, and in this case you can do that.
Upvotes: 2