├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── example.js ├── make-promises-safe.d.ts ├── make-promises-safe.js ├── package.json └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # no lockfiles here 61 | package-lock.json 62 | yarn.lock 63 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: false 3 | node_js: 4 | - '6' 5 | - '7' 6 | - '8' 7 | - '10' 8 | - '12' 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Matteo Collina 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # make-promises-safe   [![Build Status](https://travis-ci.org/mcollina/make-promises-safe.svg?branch=master)](https://travis-ci.org/mcollina/make-promises-safe) 2 | 3 | ### A Happy Note 4 | 5 | If you are using Node.js version 15+, the correct promise behaviour is already implemented and Node.js will safely behave on unhandled rejections similarly to its uncaught exception behaviour. If you are only using Node.js v15+ there is no need to use this module. 6 | 7 | If you need to support older versions of Node.js - it is a good idea to use this module to ensure future compatibility with modern Node.js versions where the safe behaviour is the default one. 8 | 9 | ## What this is 10 | 11 | A node.js module to make the use of promises safe. 12 | It implements the deprecation [DEP0018][unhandled] of Node.js in versions 6+. 13 | Using Promises without this module might cause file descriptor and memory 14 | leaks. 15 | 16 | **It is important that this module is only used in top-level program code, not 17 | in reusable modules!** 18 | 19 | ## The Problem 20 | 21 | Node.js crashes if there is an uncaught exception, while it does not 22 | crash if there is an `'unhandledRejection'`, i.e. a Promise without a 23 | `.catch()` handler. 24 | 25 | **If you are using promises, you should attach a `.catch()` handler 26 | synchronously**. 27 | 28 | As an example, the following server will leak a file descriptor because 29 | of a missing `.catch()`  handler: 30 | 31 | ```js 32 | const http = require('http') 33 | const server = http.createServer(handle) 34 | 35 | server.listen(3000) 36 | 37 | function handle (req, res) { 38 | doStuff() 39 | .then((body) => { 40 | res.end(body) 41 | }) 42 | } 43 | 44 | function doStuff () { 45 | if (Math.random() < 0.5) { 46 | return Promise.reject(new Error('kaboom')) 47 | } 48 | 49 | return Promise.resolve('hello world') 50 | } 51 | ``` 52 | 53 | ## The Solution 54 | 55 | `make-promises-safe` installs an `process.on('unhandledRejection')` 56 | handler that prints the stacktrace and exits the process with an exit 57 | code of 1, just like any uncaught exception. 58 | 59 | ## Install 60 | 61 | ``` 62 | npm install make-promises-safe --save 63 | ``` 64 | 65 | ## Usage 66 | 67 | ```js 68 | 'use strict' 69 | 70 | require('make-promises-safe') // installs an 'unhandledRejection' handler 71 | const http = require('http') 72 | const server = http.createServer(handle) 73 | 74 | server.listen(3000) 75 | 76 | function handle (req, res) { 77 | doStuff() 78 | .then((body) => { 79 | res.end(body) 80 | }) 81 | } 82 | 83 | function doStuff () { 84 | if (Math.random() < 0.5) { 85 | return Promise.reject(new Error('kaboom')) 86 | } 87 | 88 | return Promise.resolve('hello world') 89 | } 90 | ``` 91 | 92 | ### as a preloader 93 | 94 | You can add this behavior to any Node.js application by using it as a 95 | preloader: 96 | 97 | ``` 98 | node -r make-promises-safe server.js 99 | ``` 100 | 101 | ### with core dumps 102 | 103 | You can also create a core dump when an unhandled rejection occurs: 104 | 105 | 106 | ``` 107 | require('make-promises-safe').abort = true 108 | ``` 109 | 110 | ### With custom logging 111 | 112 | You can add a custom logger to log errors in your own format. To do this override the `logError` property with a function that takes a single `Error` parameter. This defaults to `console.error`. 113 | 114 | ``` 115 | const makePromisesSafe = require('make-promises-safe'); 116 | makePromisesSafe.logError = function(err) { 117 | // log the err object 118 | } 119 | ``` 120 | 121 | ## License 122 | 123 | MIT 124 | 125 | [unhandled]: https://nodejs.org/dist/latest-v8.x/docs/api/deprecations.html#deprecations_dep0018_unhandled_promise_rejections 126 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | // require('.').abort = true; 4 | const http = require('http') 5 | const server = http.createServer(handle) 6 | 7 | server.listen(3000) 8 | 9 | function handle (req, res) { 10 | doStuff() 11 | .then((body) => { 12 | res.end(body) 13 | }) 14 | } 15 | 16 | function doStuff () { 17 | if (Math.random() < 0.5) { 18 | return Promise.reject(new Error('kaboom')) 19 | } 20 | 21 | return Promise.resolve('hello world') 22 | } 23 | -------------------------------------------------------------------------------- /make-promises-safe.d.ts: -------------------------------------------------------------------------------- 1 | export let abort:string; 2 | export let logError: (...objs: any[]) => void; 3 | -------------------------------------------------------------------------------- /make-promises-safe.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const event = 'unhandledRejection' 4 | 5 | process.on(event, function (err) { 6 | module.exports.logError(err) 7 | if (module.exports.abort) { 8 | process.abort() 9 | } 10 | process.exit(1) 11 | }) 12 | 13 | module.exports.abort = false 14 | 15 | module.exports.logError = console.error 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "make-promises-safe", 3 | "version": "5.1.0", 4 | "description": "Crash or abort if you get an unhandledRejection or multipleResolves", 5 | "main": "make-promises-safe.js", 6 | "scripts": { 7 | "test": "standard | snazzy && tap test.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/mcollina/make-promises-safe.git" 12 | }, 13 | "keywords": [ 14 | "promise", 15 | "promises", 16 | "safe", 17 | "unhandled", 18 | "rejection", 19 | "unhandledRejection" 20 | ], 21 | "author": "Matteo Collina ", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/mcollina/make-promises-safe/issues" 25 | }, 26 | "homepage": "https://github.com/mcollina/make-promises-safe#readme", 27 | "devDependencies": { 28 | "pre-commit": "^1.2.2", 29 | "sinon": "^7.5.0", 30 | "snazzy": "^8.0.0", 31 | "standard": "^14.3.1", 32 | "tap": "^12.5.2" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const test = require('tap').test 4 | const path = require('path') 5 | const spawn = require('child_process').spawn 6 | 7 | const main = path.join(__dirname, require('./package').main) 8 | 9 | test('crashes the process on unhandled rejection', (t) => { 10 | t.plan(2) 11 | 12 | const child = spawn(process.execPath, [ 13 | '-r', main, '-e', 'Promise.reject(new Error(\'kaboom\'))']) 14 | 15 | child.stderr.on('data', function (chunk) { 16 | const expected = `Error: kaboom 17 | at [eval]:1:16` 18 | 19 | t.ok(chunk.toString().trim().indexOf(expected.trim()) === 0) 20 | }) 21 | 22 | child.on('close', (code) => { 23 | t.is(code, 1) 24 | }) 25 | }) 26 | 27 | test('logs error', (t) => { 28 | t.plan(1) 29 | 30 | const child = spawn(process.execPath, ['-r', main, '-e', 'require("./make-promises-safe").logError = (err) => console.log("custom", err.message); Promise.reject(new Error(\'kaboom\'))']) 31 | 32 | child.stdout.on('data', function (chunk) { 33 | const expected = 'custom kaboom' 34 | 35 | t.ok(chunk.toString().trim().indexOf(expected.trim()) === 0) 36 | }) 37 | }) 38 | --------------------------------------------------------------------------------