Search code examples
typescripthttpnock

Nock reply with 302 and 404 throws an HTTPError


I am making a function that should retry on 302 err code and return data on 200, else just throw an error.

  async retry(url: string): Promise<Response<string>> {
      const response = await got.get(url)
      switch(res.statusCode){
        case 200: {
          return response
        }
        case 302: {
          -> call login
          -> call retry again with retry(url)
        }
        default: {
          throw error
        }
      }
    }

Problem is when I setup nock like this

const scope = nock('https://airtable.com')
  .get(`/${baseID}/api/docs`)
  .reply(302)
})

Problem is that it cannot even call retry because mock returns 302 status code which internally for him throws an HTTPError which is not wanted behavior here, so is there to add tell him not to throw errors?


Solution

  • This is happening because of the default behavior of Got. It throws errors for certain status codes it deems an error.

    You can configure Got to not throw errors based on status codes by setting the throwHttpErrors option (docs).