got: Async stack traces for callback errors

What problem are you trying to solve?

I need to know the caller that generated a given http error.

Describe the feature

I use node 13 which has async stack traces but I don’t have the caller stack trace when using got. Instead I get this stack:

    err HTTPError: Response code 404 (Not Found)
        at EventEmitter.<anonymous> (.../node_modules/got/dist/
source/as-promise.js:118:31)
        at processTicksAndRejections (internal/process/task_queues.js:97:5) {
      name: 'HTTPError'
    }

I guess this happens because the connection can be used by multiple callers but there should be a way to have the whole stack.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 6
  • Comments: 23 (3 by maintainers)

Most upvoted comments

Also in case it’s helpful to any future readers using TypeScript, here’s my working TypeScript version

import got, { BeforeErrorHook, HandlerFunction, RequestError } from 'got';

const stackTraceHandler: HandlerFunction = (options, next) => {
  const context: { stack?: string } = {};
  Error.captureStackTrace(context, stackTraceHandler);
  options.context = { ...options.context, stack: context.stack };
  return next(options);
};

const addSourceStackTraceToError: BeforeErrorHook = (error: RequestError) => {
  error.stack = `${error.stack}\n---Source Stack---\n${error.options.context.stack}`;
  return error;
};

export default got.extend({
  handlers: [stackTraceHandler],
  hooks: {
    beforeError: [addSourceStackTraceToError],
  },
});

Adding the source property to the error object was causing issues so I just decided to append to the existing stack.

@szmarczak thank you for crafting this document!

We could, but:

  1. the API is marked experimental so it will give a warning (it’s live since Node.js 8.1) - but I think it’s stable for this use case as I don’t see any issues that would break this
  2. the change would be visible globally.

I think we should create another .md file and show how to achieve the desired result step-by-step.