From 754c75a958ae38f744b0895404adf1c6b1da6454 Mon Sep 17 00:00:00 2001 From: Yezen Alnafei Date: Tue, 1 Dec 2020 14:26:57 +0000 Subject: [PATCH] added request error codes --- index.d.ts | 7 ++++++- lib/transport/transport.js | 4 +++- test/transport/request.js | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index 49187b2..e3819fe 100644 --- a/index.d.ts +++ b/index.d.ts @@ -19,6 +19,11 @@ export declare type Body = string; export declare type RequestOptions = Object; export declare type ErrorObject = { message: string; + code?: string; +}; + +export declare interface CustomError extends Error { + code?: string; }; export declare type JsonResponse = { @@ -167,7 +172,7 @@ export declare class RequestTransport extends Transport { export declare class Transport { toError(err: ErrorObject, ctx: Context): Error; - createError(err: ErrorObject, ctx: Context): Error; + createError(err: ErrorObject, ctx: Context): CustomError; execute(ctx: Context): Promise; onError(ctx: Context): Function; toOptions(ctx: Context): RequestOptions; diff --git a/lib/transport/transport.js b/lib/transport/transport.js index faa130f..2fed7bd 100644 --- a/lib/transport/transport.js +++ b/lib/transport/transport.js @@ -6,7 +6,9 @@ class Transport { } createError(err, ctx) { - return new Error(`Request failed for ${ctx.req.getMethod()} ${ctx.req.getUrl()}: ${err.message}`); + const error = new Error(`Request failed for ${ctx.req.getMethod()} ${ctx.req.getUrl()}: ${err.message}`); + error.code = err.code; + return error; } execute(ctx) { diff --git a/test/transport/request.js b/test/transport/request.js index 313b38d..56d8776 100644 --- a/test/transport/request.js +++ b/test/transport/request.js @@ -270,5 +270,26 @@ describe('Request HTTP transport', () => { .catch(assert.ifError); }); + it('adds error code to request errors', () => { + nock.cleanAll(); + api + .get('/') + .delay(500) + .reply(200, simpleResponseBody); + + const ctx = createContext(url); + ctx.req.timeout(20); + + return new RequestTransport() + .execute(ctx) + .then(() => { + assert.fail('Expected request to timeout'); + }) + .catch((e) => { + assert.ok(e); + assert.equal(e.code, 'ESOCKETTIMEDOUT'); + }); + }); + }); });