Prevent “Unhandled promise rejection” error

2019-02-26 03:31发布

问题:

In my server app I want to return a "forbidden" value when the user has no permissions for the endpoint.

To this end I create a rejected promise for reuse:

export const forbidden = Promise.reject(new Error('FORBIDDEN'))

and then elsewhere in the app:

import {forbidden} from './utils'

...

    resolve: (root, {post}, {db, isCollab}) => {
        if (!isCollab) return forbidden
        return db.posts.set(post)
    },

However, when I start my app I get the warning

(node:71620) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: FORBIDDEN
(node:71620) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

How can I tell Node that this Promise is fine to be unhandled?

回答1:

I create a rejected promise for reuse

Well don't, it might be a lot easier to just create a function for reuse:

export function forbidden() { return Promise.reject(new Error('FORBIDDEN')); }

That will also get you an appropriate stack trace for the error every time you call it.

How can I tell Node that this Promise is fine to be unhandled?

Just handle it by doing nothing:

export const forbidden = Promise.reject(new Error('FORBIDDEN'));
forbidden.catch(err => { /* ignore */ }); // mark error as handled

(and don't forget to include the comment about the purpose of this seemingly no-op statement).