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?