Home > database >  getting error in string when i use throw new error
getting error in string when i use throw new error

Time:08-24

const functionName = async () => {
    try {
        //code
    } catch (error) {
        let data = {}
        data.error = error
        data.fnName = 'checkIfSupplierIsAllowedToSync'
        throw new Error(data)
    }
}


const fnName = async () => {
    try {
        await functionName()
    } catch (error) {
        console.log("error#####", error)
    }
}

answer :- error##### "[object Object]"

why i getting error in string ? how i get error with function name ?

CodePudding user response:

Error expects a string to be passed to the constructor.

[object Object] is the string representation of the simple object that was passed in.

> {}.toString()
'[object Object]'

Create an error to attach the data to, rather then an object

const functionName = async () => {
    try {
        //code
    } catch (error) {
        const wrapped_error = new Error(`Wrapped: ${error.message}`)
        wrapped_error.error = error
        error.fnName = 'checkIfSupplierIsAllowedToSync'
        throw wrapped_error
    }
}

This could be added to an Error class that encapsulates the required behaviour

class WrappedError extends Error {
  constructor(error, fnName) {
    super(`Wrapped: ${error.message}`)
    this.error = error
    this.fnName = fnName
  }
}

const functionName = async () => {
    try {
        //code
    } catch (error) {
        throw new WrappedError(error, 'checkIfSupplierIsAllowedToSync')
    }
}
  • Related