Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions lib/core/AxiosError.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function AxiosError(message, code, config, request, response) {

utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
const json = {
// Standard
message: this.message,
name: this.name,
Expand All @@ -52,6 +52,14 @@ utils.inherits(AxiosError, Error, {
code: this.code,
status: this.status
};

if (utils.isArray(this.customProps)) {
for (const customProp of this.customProps) {
json[customProp] = this[customProp];
}
}

return json;
}
});

Expand Down Expand Up @@ -95,7 +103,10 @@ AxiosError.from = (error, code, config, request, response, customProps) => {

axiosError.name = error.name;

customProps && Object.assign(axiosError, customProps);
if (customProps) {
Object.assign(axiosError, customProps);
axiosError.customProps = Object.keys(customProps);
}

return axiosError;
};
Expand Down
24 changes: 24 additions & 0 deletions test/specs/core/AxiosError.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,30 @@ describe('core::AxiosError', function() {
const error = new Error('Boom!');
expect(AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError).toBeTruthy();
});

it('should add custom properties to error that can be serialized to JSON', function() {
const error = new Error('Boom!');
const request = { path: '/foo' };
const response = { status: 200, data: { foo: 'bar' } };
const customProperties = { myCustomProperty: 'myCustomValue' };

const axiosError = AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }, request, response, customProperties);
expect(axiosError.config).toEqual({ foo: 'bar' });
expect(axiosError.code).toBe('ESOMETHING');
expect(axiosError.request).toBe(request);
expect(axiosError.response).toBe(response);
expect(axiosError.myCustomProperty).toBe('myCustomValue')
expect(axiosError.isAxiosError).toBe(true);

const json = axiosError.toJSON();
expect(json.message).toBe('Boom!');
expect(json.config).toEqual({ foo: 'bar' });
expect(json.code).toBe('ESOMETHING');
expect(json.status).toBe(200);
expect(json.request).toBe(undefined);
expect(json.response).toBe(undefined);
expect(json.myCustomProperty).toBe('myCustomValue')
});
});

it('should have status property when response was passed to the constructor', () => {
Expand Down