Skip to content
This repository has been archived by the owner on Mar 15, 2018. It is now read-only.

This software is not maintained. Rejects a promise returned by `fetch()` if status above threshold

License

Notifications You must be signed in to change notification settings

songkick/promise-reject-status-above

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

promise-reject-status-above Build Status Code Climate Test Coverage

Rejects a promise returned by fetch() if status above threshold

var rejectStatusAbove = require('@songkick/promise-reject-status-above');
var rejectAbove400 = rejectStatusAbove({status: 400});

function fetch200(){
    return fetch('/path/to/a/http-200-ok');
}

function fetch400(){
    return fetch('/path/to/a/http-400-bad-request');
}

rejectAbove400(fetch200)()
  .then(function(response){
    // the initial fetch response
  }).catch(function(err){
    // probably won't happen here, unless /200 doesn't return a HTTP - 200
  });

rejectAbove400(fetch400)()
  .then(function(response){
    // should not happen here
  }).catch(function(err){
      // err instanceof rejectStatusAbove.StatusAboveError === true
      // err === {
      //   message: 'Response status above accepted status',
      //   settings: {
      //     status: 400,
      //   },
      //   fn: fetch400,
      //   response: window.Response // the original fetch Response
      // }
  });

Options

status: positive (>= 0) number. The returned promise will be rejected if the response's status is equal or above this number.

Composition

As promise-reject-status-above input and output is a function returning a promise, you can compose them easily with other simial helpers (see below).

In the example below, our /data API is a bit janky and might return HTTP 500 errors. We'll retry them twice before giving up.

var promiseRetry = require('@songkick/promise-retry');
var rejectStatusAbove = require('@songkick/promise-reject-status-above');

var retryTwice = promiseRetry({ retries: 2 });
var rejectAbove500 = rejectStatusAbove({status: 500});

function fetchData() {
    // this call might return 500 sometimes
    return fetch('/data');
}

retryTwice(rejectAbove500(fetchData))().then(function(response){
  // yay !
}).catch(function(err){
  // we retried the call twice but always got 500s :(
});

See also

promise-reject-status-above composes really well with the following promise helper:

About

This software is not maintained. Rejects a promise returned by `fetch()` if status above threshold

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •