Skip to content

Commit

Permalink
fix(serverless): Capture custom tags in error events of GCP functions (
Browse files Browse the repository at this point in the history
…#7298)

Change the way we listen to errors by directly try/catching the function instead of listening to the domain's error callback. 

Co-authored-by: Luca Forstner <luca.forstner@sentry.io>
  • Loading branch information
Lms24 and lforst committed Feb 28, 2023
1 parent 4ae08fe commit 7029da4
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions packages/serverless/src/gcpfunction/http.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import type { AddRequestDataToEventOptions } from '@sentry/node';
import { captureException, flush, getCurrentHub } from '@sentry/node';
import { extractTraceparentData } from '@sentry/tracing';
import { baggageHeaderToDynamicSamplingContext, isString, logger, stripUrlQueryAndFragment } from '@sentry/utils';

import { domainify, getActiveDomain, proxyFunction } from './../utils';
import {
baggageHeaderToDynamicSamplingContext,
isString,
isThenable,
logger,
stripUrlQueryAndFragment,
} from '@sentry/utils';

import { domainify, proxyFunction } from './../utils';
import type { HttpFunction, WrapperOptions } from './general';

// TODO (v8 / #5257): Remove this whole old/new business and just use the new stuff
Expand Down Expand Up @@ -105,13 +111,6 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial<HttpFunctionWr
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(res as any).__sentry_transaction = transaction;

// functions-framework creates a domain for each incoming request so we take advantage of this fact and add an error handler.
// BTW this is the only way to catch any exception occured during request lifecycle.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
getActiveDomain()!.on('error', err => {
captureException(err);
});

// eslint-disable-next-line @typescript-eslint/unbound-method
const _end = res.end;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -128,6 +127,21 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial<HttpFunctionWr
});
};

return fn(req, res);
let fnResult;
try {
fnResult = fn(req, res);
} catch (err) {
captureException(err);
throw err;
}

if (isThenable(fnResult)) {
fnResult.then(null, err => {
captureException(err);
throw err;
});
}

return fnResult;
};
}

0 comments on commit 7029da4

Please sign in to comment.