简体   繁体   中英

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:

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?

obviously error.code is undefined because error is an string

The first parameter of the Error constructor expects a human-readable message , ie a String . This means that the object you're passing into new Error is being ToString ed, resulting in "[object Object]..." as the message

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

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,

try {
  // ...
} catch (err) {
  let errObject = Object.assign({}, err)
  // console.log(errObject) to see what's there and what you can use
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM