serviejs/popsicle

Catch HTTP Client Errors

Closed this issue · 1 comments

Hello, I am using popsicle and I like it pretty much. In my code I use it this way:

popsicle.request({
  method: 'POST',
  url: `${self.user.backendURL}/clients`,
  body: clientInfo,
  headers: {
    'Authorization': `Bearer ${decodeURIComponent(self.user.accessToken)}`,
    'Content-Type': 'application/json; charset=utf-8'
  }
})
.use(popsicle.plugins.parse('json'))
.then(function (response) {
  console.log('Response', response.body);
});

Doing so, I realized that I always end up in the then block when there is a HTTP response (no matter if it is a 2xx response or a 4xx response). Is there the possibility in popsicle to reject 4xx status codes (like 400, 412, etc.), so I need to catch them?

What I am thinking of is something like this:

popsicle.request({
  method: 'POST',
  url: `${self.user.backendURL}/clients`,
  body: clientInfo,
  headers: {
    'Authorization': `Bearer ${decodeURIComponent(self.user.accessToken)}`,
    'Content-Type': 'application/json; charset=utf-8'
  }
})
.use(popsicle.plugins.parse('json'))
.then(function (response) {
  // 2xx responses go here
  console.log('Success', response.body);
})
.catch(function (response) {
  // 4xx responses go here
  console.log('Client Error', response.body);
});

This shouldn't be in popsicle, it just doesn't belong here here. However, it's super common so there's a plugin for it - https://github.com/blakeembrey/popsicle-status. There are many valid reasons this isn't the default - for instance, errors vary depending on API (not every API uses status codes) and the codes themselves would need to be configurable depending on use-cases (which happens to be what plugins are great at). Also, there's a lot of middleware that should continue working just fine with a non-200 responses (e.g. caching could be able to keep track of 404s).

Edit: I would love to improve this in the README though so others don't run into it.