Skip to content

Instantly share code, notes, and snippets.

@shinokada
Created January 26, 2023 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinokada/3aa97819848c348abdec4bf0676be4f0 to your computer and use it in GitHub Desktop.
Save shinokada/3aa97819848c348abdec4bf0676be4f0 to your computer and use it in GitHub Desktop.
// reference https://dev.to/builderio/safe-data-fetching-in-modern-javascript-dp4
class ResponseError extends Error {
constructor(message, res) {
super(message)
this.response = res
}
}
export async function myFetch(...options) {
const res = await fetch(...options)
if (!res.ok) {
throw new ResponseError('Bad fetch response', res)
}
return res
}
// use it
try {
const res = await myFetch('/user')
const user = await res.json()
console.log(user)
} catch (err) {
if (err.response) {
// Handle issues via error.response.*
switch (err.response.status) {
case 400:
console.error("Bad Request - Invalid parameters or syntax")
break
case 401:
console.error("Unauthorized - Invalid or missing authentication credentials")
break
case 404:
console.error("Not Found - The requested resource could not be found")
break
case 500:
console.error("Internal Server Error - There was an error on the server")
break
default:
console.error(`An error occurred with status code: ${err.response.status}`)
}
} else {
// Handle network errors
console.error("An error occurred while trying to connect to the server")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment