Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getting error in string when i use throw new error

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading