Skip to content

Commit 81e0455

Browse files
fix(core/axios): handle un-writable error stack (#6362)
Co-authored-by: Dmitriy Mozgovoy <[email protected]>
1 parent d1d359d commit 81e0455

File tree

2 files changed

+56
-6
lines changed

2 files changed

+56
-6
lines changed

lib/core/Axios.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,15 @@ class Axios {
4646

4747
// slice off the Error: ... line
4848
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
49-
50-
if (!err.stack) {
51-
err.stack = stack;
52-
// match without the 2 top stack lines
53-
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
54-
err.stack += '\n' + stack
49+
try {
50+
if (!err.stack) {
51+
err.stack = stack;
52+
// match without the 2 top stack lines
53+
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
54+
err.stack += '\n' + stack
55+
}
56+
} catch (e) {
57+
// ignore the case where "stack" is an un-writable property
5558
}
5659
}
5760

test/unit/core/Axios.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import Axios from "../../../lib/core/Axios.js";
2+
import assert from "assert";
3+
4+
describe('Axios', function () {
5+
describe("handle un-writable error stack", function () {
6+
async function testUnwritableErrorStack(stackAttributes) {
7+
const axios = new Axios({});
8+
// mock axios._request to return an Error with an un-writable stack property
9+
axios._request = () => {
10+
const mockError = new Error("test-error");
11+
Object.defineProperty(mockError, "stack", stackAttributes);
12+
throw mockError;
13+
}
14+
try {
15+
await axios.request("test-url", {})
16+
} catch (e) {
17+
assert.strictEqual(e.message, "test-error")
18+
}
19+
}
20+
21+
it('should support errors with a defined but un-writable stack', async function () {
22+
await testUnwritableErrorStack({value: {}, writable: false})
23+
});
24+
25+
it('should support errors with an undefined and un-writable stack', async function () {
26+
await testUnwritableErrorStack({value: undefined, writable: false})
27+
});
28+
29+
it('should support errors with a custom getter/setter for the stack property', async function () {
30+
await testUnwritableErrorStack({
31+
get: () => ({}),
32+
set: () => {
33+
throw new Error('read-only');
34+
}
35+
})
36+
});
37+
38+
it('should support errors with a custom getter/setter for the stack property (null case)', async function () {
39+
await testUnwritableErrorStack({
40+
get: () => null,
41+
set: () => {
42+
throw new Error('read-only');
43+
}
44+
})
45+
});
46+
})
47+
});

0 commit comments

Comments
 (0)