superagent: Is there a way to config the 4xx & 5xx statusCode as normal response but not error

As the title presents.

I’m tired of writing code like this

const getDataAsync = co.wrap(function*(){
  let res;
  try {
    res = yield request.get('some_url')
  } catch(err) {
    if(!err.original && err.response) {
      res = err.response
    } else {
      throw err;
    }
  }
});

I have to test !err.original && err.response exists, and treat it as success response, I’m tired of writing this. So I’m asking is there a way to config that and if not can this issue be a feature request?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 19 (13 by maintainers)

Commits related to this issue

Most upvoted comments

idea: per req config

add a property or method to the superagent.Request class e.g add Request.prototype.config

request
  .get('https://www.google.com.hk')
  .config({ detectStatusCode: false }) //  <- turn off detectStatusCode here
  .end((err, res) => {
    // ... blabla
  });

I’m 👍 on this too

I think we could make the logic configurable by allowing user to supply a callback to judge whether the response is OK.

https://github.com/visionmedia/superagent/blob/v2.2.0/lib/node/index.js#L590

request.get().ok(res => res.status < 500).then(…)

(chai-http maintainer here) We’ve yet to add support for this feature in a released version of chai-http. We’ll be making a release soon. Thanks for everyone’s input here.

I think this is one of those API decisions that could go either way. Either you write application code like that to treat responses with error status codes as successful responses or you change the superagent API to treat them as success, but then you have to write application code to look at the status code in the application and respond accordingly. For example, detecting a 404 with HTML in the body when you were expecting a 200 with JSON.

I personally wish the original superagent API was “any HTTP response is success” semantics, but it’s not. This is something that would be such a breaking change I’d hesitate to change it without something as drastic as forking and renaming the project. I believe that has been discussed on github issues in the past so you might get some insight searching through closed issues for discussion.

I know of at least request-promise which has this behavior configurable:

By default, http response codes other than 2xx will cause the promise to be rejected. This can be overwritten by setting options.simple = false.

I would hesitate to make the core API configurable in this way, but I do understand your frustration.