Skip to content

Instantly share code, notes, and snippets.

@wildfrontend
Created July 21, 2020 15:36
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 wildfrontend/7d19b5fb260015455ddfa181b819e7a6 to your computer and use it in GitHub Desktop.
Save wildfrontend/7d19b5fb260015455ddfa181b819e7a6 to your computer and use it in GitHub Desktop.

prepare

  • rewrite fetch to catch httpcode
const httpCodeFetch = async ({ url, config = initialConfig }) => {
    const res = await fetch(url, config)
    if (res.status === 204) return {}
    if (res.ok) {
        return res.json()
    } else {
        const obj = await res.json()
        // new Error(res.statusText)
        throw { status: res.status, ...obj }
    }
}
  1. common code
 
 httpCodeFetch(url,...).then(res => {
    do(res)
 }).catch(err =>{
    if(err.status === 401) do401(err)
    error(err)
 })

2.try catch

 
 try{
     const res = httpCodeFetch()
     do(res)
 }catch(err){
    if(err.status === 401) do401(err)
     error(err)
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment