Skip to content

Commit

Permalink
fix!: add status as a number to GaxiosError, change code to error cod…
Browse files Browse the repository at this point in the history
…e as a string (#552)

* fix!: change code to number, and response status to string
  • Loading branch information
sofisl committed Jul 12, 2023
1 parent b9b26eb commit 88ba2e9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
23 changes: 21 additions & 2 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,38 @@ import {URL} from 'url';
/* eslint-disable @typescript-eslint/no-explicit-any */

export class GaxiosError<T = any> extends Error {
/**
* An Error code.
* See {@link https://nodejs.org/api/errors.html#errorcode error.code}
*
* @example
* 'ECONNRESET'
*/
code?: string;
response?: GaxiosResponse<T>;
config: GaxiosOptions;
/**
* An HTTP Status code.
* See {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response: status property}
*
* @example
* 500
*/
status: number;
constructor(
message: string,
options: GaxiosOptions,
response: GaxiosResponse<T>
response: GaxiosResponse<T>,
public error?: Error | NodeJS.ErrnoException
) {
super(message);
this.response = response;
this.config = options;
this.response.data = translateData(options.responseType, response.data);
this.code = response.status.toString();
if (error && 'code' in error && error.code) {
this.code = error.code;
}
this.status = response.status;
}
}

Expand Down
10 changes: 5 additions & 5 deletions test/test.getch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ describe('🚙 error handling', () => {
const scope = nock(url).get('/').reply(500);
await assert.rejects(request({url}), (err: GaxiosError) => {
scope.done();
return err.code === '500';
return err.status === 500;
});
});

it('should throw the error as a GaxiosError object, regardless of Content-Type header', async () => {
const body = {
error: {
code: 404,
status: 404,
message: 'File not found',
},
};
Expand All @@ -70,7 +70,7 @@ describe('🚙 error handling', () => {
(err: GaxiosError) => {
scope.done();
return (
err.code === '404' &&
err.status === 404 &&
err.message === 'Request failed with status code 404' &&
err.response?.data.error.message === 'File not found'
);
Expand All @@ -81,7 +81,7 @@ describe('🚙 error handling', () => {
it('should throw the error as a GaxiosError object (with the message as a string), even if the request type is requested as an arraybuffer', async () => {
const body = {
error: {
code: 404,
status: 404,
message: 'File not found',
},
};
Expand All @@ -92,7 +92,7 @@ describe('🚙 error handling', () => {
(err: GaxiosError) => {
scope.done();
return (
err.code === '404' &&
err.status === 404 &&
err.message === 'Request failed with status code 404' &&
err.response?.data.error.message === 'File not found'
);
Expand Down

0 comments on commit 88ba2e9

Please sign in to comment.