1+ 'use strict' ;
2+ const os = require ( 'os' ) ;
3+
4+ module . exports = function ( r , opts ) {
5+ opts = opts || {
6+ table : 'errors'
7+ } ;
8+
9+ if ( ! opts . filter ) {
10+ opts . filter = ( ) => true ;
11+ }
12+
13+ if ( ! typeof opts . filter === 'function' ) {
14+ throw new TypeError ( 'opts.filter must be a function' ) ;
15+ }
16+ if ( ! typeof opts . table === 'string' ) {
17+ throw new TypeError ( 'opts.table must be a string' ) ;
18+ }
19+
20+ function getStack ( errOrPromise ) {
21+ if ( errOrPromise == null ) {
22+ return null ;
23+ } else if ( errOrPromise . stack != null ) {
24+ return errOrPromise . stack ;
25+ } else {
26+ return errOrPromise ;
27+ }
28+ }
29+
30+ function insert ( errOrPromise , isPromise ) {
31+ var firstStep ;
32+
33+ if ( opts . filter ( errOrPromise ) ) {
34+ firstStep = r . table ( opts . table ) . insert ( {
35+ host : os . hostname ( ) ,
36+ pid : process . pid ,
37+ date : new Date ( ) ,
38+ stack : getStack ( errOrPromise ) ,
39+ argv : process . argv ,
40+ cwd : process . cwd ( ) ,
41+ memory : process . memoryUsage ( ) ,
42+ uptime : process . uptime ( ) ,
43+ promise : isPromise ,
44+ uid : process . getuid ( ) ,
45+ groups : process . getgroups ( ) ,
46+ load : os . loadavg ( )
47+
48+ } ) . run ( )
49+ } else {
50+ firstStep = Promise . resolve ( ) ;
51+ }
52+ firstStep
53+ . catch ( function ( err ) {
54+ // If the DB is unavailable, we would go in an infinite loop trying to keep inserting exceptions.
55+ console . error ( getStack ( err ) ) ;
56+ } )
57+
58+ return firstStep ;
59+ }
60+
61+ function handleUncaughtException ( err ) {
62+ console . error ( ( new Date ) . toUTCString ( ) + ' uncaughtException:' , getStack ( err ) )
63+ return insert ( err , false )
64+ . finally ( function ( ) {
65+ process . exit ( 1 )
66+ } )
67+ } ;
68+
69+ function handleUnhandledRejection ( reason , promise ) {
70+ console . error ( ( new Date ) . toUTCString ( ) + ' unhandledPromiseRejection:' , getStack ( reason ) )
71+ return insert ( reason , true ) ;
72+ } ;
73+
74+ process . on ( 'uncaughtException' , handleUncaughtException ) ;
75+ process . on ( 'unhandledRejection' , handleUnhandledRejection ) ;
76+ }
0 commit comments