diff --git a/lib/phin.js b/lib/phin.js index 59c165d..43a0ba5 100644 --- a/lib/phin.js +++ b/lib/phin.js @@ -13,6 +13,7 @@ const centra = require('centra') * @property {Object} [core={}] - Custom core HTTP options * @property {string} [parse=none] - Response parsing. Errors will be given if the response can't be parsed. 'none' returns body as a `Buffer`, 'json' attempts to parse the body as JSON, and 'string' attempts to parse the body as a string * @property {boolean} [followRedirects=false] - Enable HTTP redirect following +* @property {boolean} [strict=false] - Throw an error if response is not 2xx * @property {boolean} [stream=false] - Enable streaming of response. (Removes body property) * @property {boolean} [compression=false] - Enable compression for request * @property {?number} [timeout=null] - Request timeout in milliseconds @@ -63,6 +64,10 @@ const phin = async (opts) => { return await phin(opts) } + if (opts.strict && (res.statusCode < 200 || res.statusCode >= 300)) { + const details = res.body ? ` - ${res.body}` : ''; + throw new Error(`${res.statusCode} ${res.coreRes.statusMessage}${details}`) + } if (opts.stream) { res.stream = res @@ -74,7 +79,7 @@ const phin = async (opts) => { if (opts.parse) { if (opts.parse === 'json') { res.coreRes.body = await res.json() - + return res.coreRes } else if (opts.parse === 'string') { @@ -83,7 +88,7 @@ const phin = async (opts) => { return res.coreRes } } - + return res.coreRes } } diff --git a/types.d.ts b/types.d.ts index 9e09774..d974a44 100644 --- a/types.d.ts +++ b/types.d.ts @@ -9,6 +9,7 @@ interface IOptionsBase { headers?: object core?: http.ClientRequestArgs followRedirects?: boolean + strict?: boolean stream?: boolean compression?: boolean timeout?: number @@ -43,7 +44,7 @@ declare namespace phin { export type IWithData = T & { data: string | Buffer | object; } - + export type IWithForm = T & { form: { [index: string]: string