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
Advertisement
Answer
The first parameter of the Error
constructor expects a human-readable message, i.e. 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, i.e.
try { // ... } catch (err) { console.log('error', err); const error = new Error(err.message); error.code = err.code; // other stuff throw error; }
or
class MMError extends Error { constructor(message, code) { super(message); this.code = code; // other stuff } } // ... try { // ... } catch (err) { console.log('error', err); const error = new MMError(err.message, err.code); throw error; }