简体   繁体   中英

Handling status 500 with try and catch

I can't tell what is the optimal way to handle the status 500 sent by my API. Could you please help me? In the case below, when my API responds with a status 500, I wish to set an error message in my redux store. When my API sent a successful status code, I wish to "Fetch the user decks" in my store.

My first attempt felt logical and dry to me, but it did not work:

const createDeck = async () => {
        try {
          const request = await fetch(`${back}/deck/`, options)
          const response = await request.json()
          store.dispatch({ type: FETCH_USER_DECKS })
        } catch (error) {
          store.dispatch({ type: SET_ERROR, message: error })
        }
      }

When the API send a 500 status, no exception seems to be thrown and the code in my catch block is ignored.

My second and third attempt worked as I excepted them too, but they feel convoluted and weird:

2nd attempt:

 const createDeck = async () => {
        try {
          const request = await fetch(`${back}/deck/`, options)
          const response = await request.json()
          if (request.status === 201 || request.status === 200) {
            store.dispatch({ type: FETCH_USER_DECKS })
          } else {
          store.dispatch({ type: SET_ERROR, message: error })
          }
        } catch (error) {
          console.log('error')
        }
  }

This works, but it ignores completely the catch block, making me wonder: what's even the point of try...catch then?

Third attempt:

  const createDeck = async () => {
    try {
      const request = await fetch(`${back}/deck/`, options)
      const response = await request.json()
      if (request.status === 201 || request.status === 200) {
        store.dispatch({ type: FETCH_USER_DECKS })
      } else {
        throw response
      }
    } catch (error) {
      store.dispatch({ type: SET_ERROR, message: error })
    }
  }

This third attempt make use of catch, but it feels weird to manually throw an exception, to be immediately caught by catch.

Am I missing something here?

Isbn has properly answered this in the comments. I'm putting it here again for visibility: "Since you're using fetch() it would probably make sense to adopt its implementation model and to not consider a 500 response as an exception (attempt 2). But I wouldn't see anything wrong with your third attempt either (axios, for example, would raise an error in that case). Note that fetch() response exposes a ok property to check whether the request succeeded or not"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM