_error.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. const core = require('@sentry/core');
  3. const responseEnd = require('./utils/responseEnd.js');
  4. /**
  5. * Capture the exception passed by nextjs to the `_error` page, adding context data as appropriate.
  6. *
  7. * @param contextOrProps The data passed to either `getInitialProps` or `render` by nextjs
  8. */
  9. async function captureUnderscoreErrorException(contextOrProps) {
  10. const { req, res, err } = contextOrProps;
  11. // 404s (and other 400-y friends) can trigger `_error`, but we don't want to send them to Sentry
  12. const statusCode = (res && res.statusCode) || contextOrProps.statusCode;
  13. if (statusCode && statusCode < 500) {
  14. return Promise.resolve();
  15. }
  16. // In previous versions of the suggested `_error.js` page in which this function is meant to be used, there was a
  17. // workaround for https://github.com/vercel/next.js/issues/8592 which involved an extra call to this function, in the
  18. // custom error component's `render` method, just in case it hadn't been called by `getInitialProps`. Now that that
  19. // issue has been fixed, the second call is unnecessary, but since it lives in user code rather than our code, users
  20. // have to be the ones to get rid of it, and guaraneteedly, not all of them will. So, rather than capture the error
  21. // twice, we just bail if we sense we're in that now-extraneous second call. (We can tell which function we're in
  22. // because Nextjs passes `pathname` to `getInitialProps` but not to `render`.)
  23. if (!contextOrProps.pathname) {
  24. return Promise.resolve();
  25. }
  26. core.withScope(scope => {
  27. if (req) {
  28. scope.setSDKProcessingMetadata({ request: req });
  29. }
  30. // If third-party libraries (or users themselves) throw something falsy, we want to capture it as a message (which
  31. // is what passing a string to `captureException` will wind up doing)
  32. core.captureException(err || `_error.js called with falsy error (${err})`, {
  33. mechanism: {
  34. type: 'instrument',
  35. handled: false,
  36. data: {
  37. function: '_error.getInitialProps',
  38. },
  39. },
  40. });
  41. });
  42. // In case this is being run as part of a serverless function (as is the case with the server half of nextjs apps
  43. // deployed to vercel), make sure the error gets sent to Sentry before the lambda exits.
  44. await responseEnd.flushQueue();
  45. }
  46. exports.captureUnderscoreErrorException = captureUnderscoreErrorException;
  47. //# sourceMappingURL=_error.js.map