11import { getCurrentHub , Scope } from '@sentry/core' ;
22import { Integration } from '@sentry/types' ;
3+ import { consoleSandbox } from '@sentry/utils' ;
4+
5+ import { logAndExitProcess } from '../handlers' ;
6+
7+ type UnhandledRejectionMode = 'none' | 'warn' | 'strict' ;
38
49/** Global Promise Rejection handler */
510export class OnUnhandledRejection implements Integration {
@@ -12,6 +17,19 @@ export class OnUnhandledRejection implements Integration {
1217 */
1318 public static id : string = 'OnUnhandledRejection' ;
1419
20+ /**
21+ * @inheritDoc
22+ */
23+ public constructor (
24+ private readonly _options : {
25+ /**
26+ * Option deciding what to do after capturing unhandledRejection,
27+ * that mimicks behavior of node's --unhandled-rejection flag.
28+ */
29+ mode : UnhandledRejectionMode ;
30+ } = { mode : 'warn' } ,
31+ ) { }
32+
1533 /**
1634 * @inheritDoc
1735 */
@@ -28,6 +46,7 @@ export class OnUnhandledRejection implements Integration {
2846 const hub = getCurrentHub ( ) ;
2947
3048 if ( ! hub . getIntegration ( OnUnhandledRejection ) ) {
49+ this . _handleRejection ( reason ) ;
3150 return ;
3251 }
3352
@@ -49,5 +68,31 @@ export class OnUnhandledRejection implements Integration {
4968
5069 hub . captureException ( reason , { originalException : promise } ) ;
5170 } ) ;
71+
72+ this . _handleRejection ( reason ) ;
73+ }
74+
75+ /**
76+ * Handler for `mode` option
77+ */
78+ private _handleRejection ( reason : any ) : void {
79+ // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240
80+ const rejectionWarning =
81+ 'This error originated either by ' +
82+ 'throwing inside of an async function without a catch block, ' +
83+ 'or by rejecting a promise which was not handled with .catch().' +
84+ ' The promise rejected with the reason:' ;
85+
86+ if ( this . _options . mode === 'warn' ) {
87+ consoleSandbox ( ( ) => {
88+ console . warn ( rejectionWarning ) ;
89+ console . error ( reason && reason . stack ? reason . stack : reason ) ;
90+ } ) ;
91+ } else if ( this . _options . mode === 'strict' ) {
92+ consoleSandbox ( ( ) => {
93+ console . warn ( rejectionWarning ) ;
94+ } ) ;
95+ logAndExitProcess ( reason ) ;
96+ }
5297 }
5398}
0 commit comments