├── .editorconfig ├── .gitattributes ├── .github ├── funding.yml ├── security.md └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── fixture-custom-log.js ├── fixture.js ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md ├── register.d.ts ├── register.js └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/funding.yml: -------------------------------------------------------------------------------- 1 | github: sindresorhus 2 | open_collective: sindresorhus 3 | tidelift: npm/loud-rejection 4 | custom: https://sindresorhus.com/donate 5 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 14 14 | - 12 15 | - 10 16 | - 8 17 | steps: 18 | - uses: actions/checkout@v2 19 | - uses: actions/setup-node@v1 20 | with: 21 | node-version: ${{ matrix.node-version }} 22 | - run: npm install 23 | - run: npm test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | .nyc_output 4 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /fixture-custom-log.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const loudRejection = require('.'); 3 | 4 | loudRejection(string => { 5 | console.log('custom-log', string); 6 | }); 7 | 8 | Promise.reject(new Error('foo')); 9 | -------------------------------------------------------------------------------- /fixture.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const Promise = require('bluebird'); 3 | const loudRejection = require('.'); 4 | 5 | loudRejection(); 6 | 7 | const promises = {}; 8 | 9 | console.log('started'); 10 | 11 | function reject(key, reason) { 12 | // IMPORTANT: key is always logged to stdout 13 | // Make sure to remember that when grepping output (keep key and message different). 14 | console.log('Rejecting:', key); 15 | promises[key] = new Promise(((resolve, reject) => { 16 | reject(reason); 17 | })); 18 | } 19 | 20 | function handle(key) { 21 | promises[key].catch(() => {}); 22 | } 23 | 24 | process.on('message', message => { 25 | switch (message.action) { 26 | case 'reject-error': 27 | return reject(message.key, new Error(message.message)); 28 | case 'reject-value': 29 | return reject(message.key, message.value); 30 | case 'reject-nothing': 31 | return reject(message.key); 32 | case 'reinstall': 33 | return loudRejection(); 34 | case 'handle': 35 | return handle(message.key); 36 | default: 37 | console.error('Unknown message received:', message); 38 | process.exit(1); 39 | } 40 | }); 41 | 42 | process.send({status: 'ready'}); 43 | 44 | setTimeout(() => {}, 30000); 45 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | declare const loudRejection: { 2 | /** 3 | Make unhandled promise rejections fail loudly instead of the default [silent fail](https://gist.github.com/benjamingr/0237932cee84712951a2). 4 | 5 | @param log - Custom logging function to print the rejected promise. Receives the error stack. Default: `console.error`. 6 | 7 | @example 8 | ``` 9 | import loudRejection = require('loud-rejection'); 10 | import promiseFunction = require('promise-fn'); 11 | 12 | // Install the `unhandledRejection` listeners 13 | loudRejection(); 14 | 15 | promiseFunction(); 16 | ``` 17 | */ 18 | (log?: (stack: string) => void): void; 19 | 20 | // TODO: remove this in the next major version, refactor the whole definition to: 21 | // declare function loudRejection(log?: (stack: string) => void): void; 22 | // export = loudRejection; 23 | default: typeof loudRejection; 24 | }; 25 | 26 | export = loudRejection; 27 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const util = require('util'); 3 | const onExit = require('signal-exit'); 4 | const currentlyUnhandled = require('currently-unhandled'); 5 | 6 | let installed = false; 7 | 8 | const loudRejection = (log = console.error) => { 9 | if (installed) { 10 | return; 11 | } 12 | 13 | installed = true; 14 | 15 | const listUnhandled = currentlyUnhandled(); 16 | 17 | onExit(() => { 18 | const unhandledRejections = listUnhandled(); 19 | 20 | if (unhandledRejections.length > 0) { 21 | for (const unhandledRejection of unhandledRejections) { 22 | let error = unhandledRejection.reason; 23 | 24 | if (!(error instanceof Error)) { 25 | error = new Error(`Promise rejected with value: ${util.inspect(error)}`); 26 | } 27 | 28 | log(error.stack); 29 | } 30 | 31 | process.exitCode = 1; 32 | } 33 | }); 34 | }; 35 | 36 | module.exports = loudRejection; 37 | // TODO: remove this in the next major version 38 | module.exports.default = loudRejection; 39 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import loudRejection = require('.'); 3 | import './register'; 4 | 5 | expectType(loudRejection()); 6 | expectType(loudRejection(console.log)); 7 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "loud-rejection", 3 | "version": "2.2.0", 4 | "description": "Make unhandled promise rejections fail loudly instead of the default silent fail", 5 | "license": "MIT", 6 | "repository": "sindresorhus/loud-rejection", 7 | "author": { 8 | "name": "Sindre Sorhus", 9 | "email": "sindresorhus@gmail.com", 10 | "url": "sindresorhus.com" 11 | }, 12 | "engines": { 13 | "node": ">=8" 14 | }, 15 | "scripts": { 16 | "test": "xo && nyc ava && tsd" 17 | }, 18 | "files": [ 19 | "index.js", 20 | "index.d.ts", 21 | "register.js", 22 | "register.d.ts" 23 | ], 24 | "keywords": [ 25 | "promise", 26 | "promises", 27 | "unhandled", 28 | "uncaught", 29 | "rejection", 30 | "loud", 31 | "fail", 32 | "catch", 33 | "throw", 34 | "handler", 35 | "exit", 36 | "debug", 37 | "debugging", 38 | "verbose" 39 | ], 40 | "dependencies": { 41 | "currently-unhandled": "^0.4.1", 42 | "signal-exit": "^3.0.2" 43 | }, 44 | "devDependencies": { 45 | "ava": "^1.4.1", 46 | "bluebird": "^3.5.3", 47 | "coveralls": "^3.0.3", 48 | "delay": "^4.1.0", 49 | "execa": "^1.0.0", 50 | "get-stream": "^5.0.0", 51 | "nyc": "^13.3.0", 52 | "tsd": "^0.7.1", 53 | "xo": "^0.24.0" 54 | }, 55 | "nyc": { 56 | "exclude": [ 57 | "fixture.js" 58 | ] 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # loud-rejection 2 | 3 | > Make unhandled promise rejections fail loudly instead of the default [silent fail](https://gist.github.com/benjamingr/0237932cee84712951a2) 4 | 5 | By default, promises fail silently if you don't attach a `.catch()` handler to them. 6 | 7 | This tool keeps track of unhandled rejections globally. If any remain unhandled at the end of your process, it logs them to STDERR and exits with code 1. 8 | 9 | Use this in top-level things like tests, CLI tools, apps, etc, **but not in reusable modules.**
10 | Not needed in the browser as unhandled rejections are shown in the console. 11 | 12 | **With [Node.js 15](https://medium.com/@nodejs/node-js-v15-0-0-is-here-deb00750f278), this package is moot as the default behavior then is to throw on unhandled rejections.** 13 | 14 | 15 | ## Install 16 | 17 | ``` 18 | $ npm install loud-rejection 19 | ``` 20 | 21 | 22 | ## Usage 23 | 24 | ```js 25 | const loudRejection = require('loud-rejection'); 26 | const promiseFunction = require('promise-fn'); 27 | 28 | // Install the `unhandledRejection` listeners 29 | loudRejection(); 30 | 31 | promiseFunction(); 32 | ``` 33 | 34 | Without this module it's more verbose and you might even miss some that will fail silently: 35 | 36 | ```js 37 | const promiseFunction = require('promise-fn'); 38 | 39 | function error(error) { 40 | console.error(error.stack); 41 | process.exit(1); 42 | } 43 | 44 | promiseFunction().catch(error); 45 | ``` 46 | 47 | ### Register script 48 | 49 | Alternatively to the above, you may simply require `loud-rejection/register` and the unhandledRejection listener will be automagically installed for you. 50 | 51 | This is handy for ES2015 imports: 52 | 53 | ```js 54 | import 'loud-rejection/register'; 55 | ``` 56 | 57 | 58 | ## API 59 | 60 | ### loudRejection([log]) 61 | 62 | #### log 63 | 64 | Type: `Function`
65 | Default: `console.error` 66 | 67 | Custom logging function to print the rejected promise. Receives the error stack. 68 | 69 | 70 | ## Related 71 | 72 | - [hard-rejection](https://github.com/sindresorhus/hard-rejection) - Make unhandled promise rejections fail hard right away instead of the default silent fail 73 | - [More…](https://github.com/sindresorhus/promise-fun) 74 | 75 | 76 | --- 77 | 78 |
79 | 80 | Get professional support for this package with a Tidelift subscription 81 | 82 |
83 | 84 | Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. 85 |
86 |
87 | -------------------------------------------------------------------------------- /register.d.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sindresorhus/loud-rejection/4457733fe5c41f3c7d28a51da1d07922461b9b16/register.d.ts -------------------------------------------------------------------------------- /register.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | require('.')(); 3 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import {fork} from 'child_process'; 2 | import test from 'ava'; 3 | import getStream from 'get-stream'; 4 | import delay from 'delay'; 5 | import execa from 'execa'; 6 | 7 | // Slow things down for reliable tests on CI. 8 | const tick = time => delay(process.env.CI ? time * 10 : time); 9 | 10 | test.beforeEach.cb(t => { 11 | const child = fork('fixture.js', {silent: true}); 12 | 13 | const exit = new Promise((resolve, reject) => 14 | child.on('exit', exitCode => 15 | (exitCode > 0 ? reject : resolve)(exitCode) 16 | ) 17 | ); 18 | 19 | t.context = { 20 | // Tell the child to create a promise, and reject it 21 | rejectWithError: (key, message) => child.send({ 22 | action: 'reject-error', 23 | key, 24 | message 25 | }), 26 | rejectWithValue: (key, value) => child.send({ 27 | action: 'reject-value', 28 | key, 29 | value 30 | }), 31 | rejectWithNothing: key => child.send({ 32 | action: 'reject-nothing', 33 | key 34 | }), 35 | 36 | // Tell the child to handle the promise previously rejected 37 | handle: key => child.send({ 38 | action: 'handle', 39 | key 40 | }), 41 | 42 | // Tell the child to reinstall loudRejection 43 | reinstall: () => child.send({action: 'reinstall'}), 44 | 45 | // Kill the child (returns a promise for when the child is done) 46 | kill: () => { 47 | child.kill(); 48 | return exit; 49 | }, 50 | 51 | // The stdout of the child. Useful for debug 52 | stdout: getStream(child.stdout), 53 | 54 | // The stderr of the child. This is where unhandledRejections will be logged 55 | stderr: getStream(child.stderr), 56 | 57 | // Promise for when the child has exited 58 | exit 59 | }; 60 | 61 | child.on('message', message => { 62 | if (message.status !== 'ready') { 63 | t.fail(`I got a message I don't understand: ${JSON.stringify(message)}`); 64 | } 65 | 66 | t.end(); 67 | }); 68 | }); 69 | 70 | test('no rejections', async t => { 71 | const child = t.context; 72 | 73 | await tick(20); 74 | await child.kill(); 75 | 76 | t.is(await child.stderr, ''); 77 | }); 78 | 79 | test('one unhandled rejection', async t => { 80 | const child = t.context; 81 | 82 | child.rejectWithError('a', 'foo123'); 83 | await tick(20); 84 | await child.kill(); 85 | 86 | t.regex(await child.stderr, /foo123/); 87 | }); 88 | 89 | test('two unhandled rejections', async t => { 90 | const child = t.context; 91 | 92 | child.rejectWithError('a', 'foo456'); 93 | child.rejectWithError('b', 'bar789'); 94 | await tick(20); 95 | await child.kill(); 96 | 97 | t.regex(await child.stderr, /foo456/); 98 | t.regex(await child.stderr, /bar789/); 99 | }); 100 | 101 | test('one rejection that is handled before exit', async t => { 102 | const child = t.context; 103 | 104 | child.rejectWithError('a', 'foo123'); 105 | await tick(20); 106 | child.handle('a'); 107 | await tick(20); 108 | await child.kill(); 109 | 110 | t.is(await child.stderr, ''); 111 | }); 112 | 113 | test('two rejections, first one handled', async t => { 114 | const child = t.context; 115 | 116 | child.rejectWithError('a', 'foo987'); 117 | child.rejectWithError('b', 'bar654'); 118 | await tick(20); 119 | child.handle('a'); 120 | await tick(20); 121 | await child.kill(); 122 | 123 | t.false(/foo987/.test(await child.stderr)); 124 | t.regex(await child.stderr, /bar654/); 125 | }); 126 | 127 | test('two rejections, last one handled', async t => { 128 | const child = t.context; 129 | 130 | child.rejectWithError('a', 'foo987'); 131 | child.rejectWithError('b', 'bar654'); 132 | await tick(20); 133 | child.handle('b'); 134 | await tick(20); 135 | await child.kill(); 136 | 137 | t.regex(await child.stderr, /foo987/); 138 | t.false(/bar654/.test(await child.stderr)); 139 | }); 140 | 141 | test('rejection with a string value', async t => { 142 | const child = t.context; 143 | 144 | child.rejectWithValue('a', 'foo123'); 145 | await tick(20); 146 | await child.kill(); 147 | 148 | t.regex(await child.stderr, /Promise rejected with value: 'foo123'/); 149 | }); 150 | 151 | test('rejection with a falsy value', async t => { 152 | const child = t.context; 153 | 154 | child.rejectWithValue('a', false); 155 | child.rejectWithValue('a', 0); 156 | await tick(20); 157 | await child.kill(); 158 | 159 | t.regex(await child.stderr, /Promise rejected with value: false/); 160 | t.regex(await child.stderr, /Promise rejected with value: 0/); 161 | }); 162 | 163 | test('rejection with no value', async t => { 164 | const child = t.context; 165 | 166 | child.rejectWithNothing(); 167 | await tick(20); 168 | await child.kill(); 169 | 170 | t.regex(await child.stderr, /Promise rejected with value: undefined/); 171 | }); 172 | 173 | test('custom log function', async t => { 174 | // TODO: use execa `reject: false` option 175 | const stdout = await execa('node', ['fixture-custom-log.js']).catch(error => error.stdout); 176 | t.is(stdout.split('\n')[0], 'custom-log Error: foo'); 177 | }); 178 | --------------------------------------------------------------------------------