[英]Why when i generate an Error i am getting an String Error?
i am getting several error, that is ok, when the user reject, when the transaction was bad, and so on我收到了几个错误,没关系,当用户拒绝时,当交易不好时,等等
but now i want to show differents message by their code error但现在我想通过他们的代码错误显示不同的消息
in my service of my project i am getting this error在我的项目服务中,我收到了这个错误
{code: 4001, message: 'MetaMask Tx Signature: User denied transaction', stack: '{\n "code": 4001,\n "message": "MetaMask Tx'}
this is my code这是我的代码
function getInformation=()=>{
try{
...
} catch (err) {
error = err
console.log('error', error) // error is the up message
throw new Error(error)
}
}
then i am using the getInformation function like this:然后我像这样使用getInformation function:
try{
...
const info= getInformation()
} catch (error) {
console.log('EERROR', error,error.code)
here i see the error as string在这里,我将错误视为字符串
EERROR Error: [object Object]
at _callee$ (PWDService.js?9579:13)
at tryCatch (runtime.js?96cf:62)
at Generator.invoke [as _invoke] (runtime.js?96cf:296), undefined
and error.code
is undefined, why i am getting as a string and error.code
as undefined?并且
error.code
是未定义的,为什么我得到一个字符串而error.code
是未定义的?
obviously error.code
is undefined because error is an string显然
error.code
是未定义的,因为 error 是一个字符串
The first parameter of the Error
constructor expects a human-readable message , ie a String . Error
构造函数的第一个参数需要一个人类可读的消息,即一个字符串。 This means that the object you're passing into new Error
is being ToString
ed, resulting in "[object Object]..."
as the message这意味着您传递给
new Error
的object正在被ToString
编辑,导致"[object Object]..."
作为消息
If you are happy with the error coming into the initial catch, simply re-throw如果您对最初捕获的错误感到满意,只需重新抛出
try {
// ...
} catch (err) {
console.log('error', err);
throw err;
}
If you want to create a new custom error, you'll need to create it by either modifying the new Error
or creating your own Error class , ie如果要创建新的自定义错误,则需要通过修改
new Error
或创建自己的错误 class来创建它,即
try {
// ...
} catch (err) {
console.log('error', err);
const error = new Error(err.message);
error.code = err.code;
// other stuff
throw err;
}
or或者
class MMError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
// ...
try {
// ...
} catch (err) {
console.log('error', err);
const error = new MMError(err.message, err.code);
throw err;
}
@react1 you can always reconstruct the error and see all of its properties by doing something similar to below, @react1,您始终可以通过执行类似于下面的操作来重建错误并查看其所有属性,
try {
// ...
} catch (err) {
let errObject = Object.assign({}, err)
// console.log(errObject) to see what's there and what you can use
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.