Superagent: Any way to get 4xx response body w/o try...catch while using await?

Created on 18 Nov 2017  路  2Comments  路  Source: visionmedia/superagent

async function checkToken(token) {
  const result = await superagent
    .post(`${config.serviceUrl}/check_token`)
    .send({token});
  return result.body;
}

Default options if this call will return 401 throws an Exception, which is not what i expect. API i call is using HTTP status messages also as body to give information back and i just need the body part.

Response with http status 401 is

{
    "data": null,
    "error": {
        "code": "INVALID_TOKEN",
        "message": "Token is not valid"
    }
}

And currently, to get this, I need to wrap all superagent calls with try...catch

async function checkToken(token) {
  let result = null;
  try {
    result = await superagent
      .post(`${config.serviceUrl}/check_token`)
      .send({token});
  } catch (e) {
    result = e.response;
  }
  return result.body;
}

Any way to have the 1st sample working and returning JSON w/o looking at HTTP status?

Most helpful comment

There's .ok() callback which lets you decide which responses are considered sucessful.

All 2 comments

There's .ok() callback which lets you decide which responses are considered sucessful.

In case if anyone else would found this issue:

In Jest you can

const response = superAgent.get(url)
await expect(response).rejects.toMatchObject({
  status: 400,
  response: {
    text: '[expected error message]'
  }
})

Code for Chai or Should.js would be very similar

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tbo picture tbo  路  4Comments

littlee picture littlee  路  5Comments

tj picture tj  路  9Comments

tj picture tj  路  4Comments

srohde picture srohde  路  8Comments