Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

node.js - Prevent "Unhandled promise rejection" error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...