防止“未处理的承诺被拒绝";错误 [英] Prevent "Unhandled promise rejection" error

查看:199
本文介绍了防止“未处理的承诺被拒绝";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的服务器应用中,当用户没有端点权限时,我想返回一个禁止"值.

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.

如何告诉Node这个Promise可以解决?

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

推荐答案

我创建了被拒绝的重用承诺

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.

如何告诉Node这个Promise可以解决?

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

这篇关于防止“未处理的承诺被拒绝";错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆