Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve stacktrace when wrapping errors #935

Merged
merged 4 commits into from
Nov 23, 2019
Merged
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
18 changes: 16 additions & 2 deletions source/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export class GotError extends Error {
code?: string;
readonly options: NormalizedOptions;

constructor(message: string, error: (Error & {code?: string}) | {code?: string}, options: NormalizedOptions) {
constructor(message: string, error: Partial<Error & {code?: string}>, options: NormalizedOptions) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'GotError';
Expand All @@ -19,6 +19,20 @@ export class GotError extends Error {
Object.defineProperty(this, 'options', {
value: options
});

// Recover the original stacktrace
if (!is.undefined(error.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse();

// Remove duplicated traces
while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
thisStackTrace.shift();
}

this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
}

Expand Down Expand Up @@ -96,7 +110,7 @@ export class TimeoutError extends GotError {
event: string;

constructor(error: TimedOutError, timings: Timings, options: NormalizedOptions) {
super(error.message, {code: 'ETIMEDOUT'}, options);
super(error.message, error, options);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
Expand Down
11 changes: 9 additions & 2 deletions source/request-as-event-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {CacheError, MaxRedirectsError, RequestError, TimeoutError} from './error
import urlToOptions from './utils/url-to-options';
import {NormalizedOptions, Response, ResponseObject} from './utils/types';

const setImmediateAsync = () => new Promise(resolve => setImmediate(resolve));
const pipeline = promisify(stream.pipeline);

const redirectCodes: ReadonlySet<number> = new Set([300, 301, 302, 303, 304, 307, 308]);
Expand Down Expand Up @@ -283,7 +284,13 @@ export default (options: NormalizedOptions) => {
}
};

setImmediate(async () => {
(async () => {
// Promises are executed immediately.
// If there were no `setImmediate` here,
// `promise.json()` would have no effect
// as the request would be sent already.
await setImmediateAsync();

try {
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
Expand All @@ -294,7 +301,7 @@ export default (options: NormalizedOptions) => {
} catch (error) {
emitError(error);
}
});
})();

return emitter;
};
Expand Down
14 changes: 14 additions & 0 deletions test/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,17 @@ test('errors are thrown directly when options.stream is true', t => {
message: 'Parameter `hooks` must be an Object, not boolean'
});
});

test('the old stacktrace is recovered', async t => {
const error = await t.throwsAsync(got('https://example.com', {
request: () => {
throw new Error('foobar');
}
}));

t.true(error.stack.includes('at Object.request'));

// The first `at get` points to where the error was wrapped,
// the second `at get` points to the real cause.
Copy link
Collaborator Author

@szmarczak szmarczak Nov 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now:

GotError: foobar
    at get (/home/szm/Desktop/got/source/request-as-event-emitter.ts:250:15)
+   at Object.request (/home/szm/Desktop/got/test/error.ts:206:10)
+   at get (/home/szm/Desktop/got/source/request-as-event-emitter.ts:248:31)
    at Immediate.<anonymous> (/home/szm/Desktop/got/source/request-as-event-emitter.ts:313:4)

Before:

GotError: foobar
    at get (/home/szm/Desktop/got/source/request-as-event-emitter.ts:250:15)
    -- the line above only points to where the error was captured  --
	-- missing what caused the error --
    at Immediate.<anonymous> (/home/szm/Desktop/got/source/request-as-event-emitter.ts:313:4)

t.not(error.stack.indexOf('at get'), error.stack.lastIndexOf('at get'));
});