node.jssuperagent

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


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?


Solution

  • Superagent by default treats every 4xx and 5xx response as error. You can however tell it, which responses you consider as error, by using .ok.

    Sample example from documentation (https://visionmedia.github.io/superagent/#error-handling),

    request.get('/404')
     .ok(res => res.status < 500)
     .then(response => {
       // reads 404 page as a successful response
    })
    

    If the function inside the .ok, returns true then it will not be considered as error case.