Skip to content

Commit

Permalink
fix: extract toError helper for common error shapes
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed May 13, 2019
1 parent 6d47bc7 commit 3535f34
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* `Promise`- based HTTP requestor
* Works with HTTP and HTTPS protocols
* Automatically handles JSON requests and responses
* Extremely lightweight with **no dependencies** – 649 bytes!
* Extremely lightweight with **no dependencies** 678 bytes!
* Includes aliases for common HTTP verbs: `get`, `post`, `put`, `patch`, and `del`

Additionally, this module is delivered as:
Expand Down
18 changes: 11 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import { request } from 'https';
import { globalAgent } from 'http';
import { parse, resolve } from 'url';

function toError(rej, res, err) {
err = err || new Error(res.statusMessage);
err.statusMessage = res.statusMessage;
err.statusCode = res.statusCode;
err.headers = res.headers;
err.data = res.data;
rej(err);
}

export function send(method, uri, opts={}) {
return new Promise((res, rej) => {
let out = '';
Expand All @@ -24,17 +33,12 @@ export function send(method, uri, opts={}) {
try {
out = JSON.parse(out, opts.reviver);
} catch (err) {
return rej(err);
return toError(rej, r, err);
}
}
r.data = out;
if (r.statusCode >= 400) {
let err = new Error(r.statusMessage);
err.statusMessage = r.statusMessage;
err.statusCode = r.statusCode;
err.headers = r.headers;
err.data = r.data;
rej(err);
toError(rej, r);
} else if (r.statusCode > 300 && redirect && r.headers.location) {
opts.path = resolve(opts.path, r.headers.location);
return send(method, opts.path.startsWith('/') ? opts : opts.path, opts).then(res, rej);
Expand Down

0 comments on commit 3535f34

Please sign in to comment.