gpt4 book ai didi

javascript - 通用 throw 给出 Expected an object to be thrown lint error

转载 作者:数据小太阳 更新时间:2023-10-29 05:00:46 24 4
gpt4 key购买 nike

下面抛出代码给出 lint 错误 Expected an object to be thrown no-throw-literal

throw { code : 403, message : myMessage };

如果我尝试抛出新错误,我不会得到 eslint,但它会在响应中给出 [Object Object]。

throw new Error({ code : 403, message : myMessage });

有人能告诉我如何解决 Expected an object to be thrown 错误吗?无需删除 eslint 配置/规则

最佳答案

 throw Object.assign(
new Error(myMessage),
{ code: 402 }
);

抛出常规错误并使用自定义字段对其进行扩展。


您还可以为此编写一个可重用的错误类:

  class CodeError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}

throw new CodeError(myMessage, 404);

这样,您可以在捕获时轻松区分错误:

  } catch(error) {
if(error instanceof CodeError) {
console.log(error.code);
} else {
//...
}
}

关于javascript - 通用 throw 给出 Expected an object to be thrown lint error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53080948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com