More like JavaScript question then a React one, but since the problem I have is in a React app, guess the title is correct.
Anyway. I have an object which contains API error codes like this:
const apiErrors = {
"500": "System is currently unavailable. Please contact you system administrator or try again later",
"404": "There was a problem with your request. Please contact support",
"403": "Access denied",
"408": "Your request timed out.",
"default": "Oops! Lorem ipsum dolor sit amet"
}
In my component I have the API response with the error status. Now I want to compare the error status, if there's any, and show the correct friendly error. Something like:
componentDidUpdate(prevProps) {
// map the object keys of apiErrors
// compare it with the API error status
if (this.props.error.response.status === apiErrors[i]//example: 403) {
//show the corresponding error from the apiErrors
//in this case 403 error "Access denied"
}
}
But I don't know exactly how to do the comparison and show the correct message!
apiErrors.hasOwnProperty(errorCode)this.props.error.response.statusis one of theapiErrors? What are the possible values ofthis.props.error.response.status?this.props.error.response.statusis supposed to be 500 or 404 or 403, etc. So you could doif (apiErrors.hasOwnProperty(this.props.error.response.status)) { var message = apiErrors(this.props.error.response.status);... }