Home > front end >  Throw new Error with Object in TypeScript Jest
Throw new Error with Object in TypeScript Jest

Time:12-19

How do I throw a new Error with Object containing Error details in typeScript?

I am using jest for testing typescript code and I want to throw new Error as shown below:

mock.spyOn(AppUtils,'util_plane').mockImplementation(() => {
        throw new Error("Error Message",{status:403})
})

when I do this, the compiler complains saying:

Expected 0-1 arguments, but got 2.ts(2554)

CodePudding user response:

Error constructor doesn't expect {status: number} to be passed to it. You can create and use custom error class:

class CustomError extends Error {
    status: number;

    constructor(message: string, { status }: { status: number }) {
        super(message);
        this.status = status
    }
}

// ...

throw new CustomError('Error Message', { status: 403 })

Or you could assign status property to the error after creation:

throw Object.assign(new Error('Error Message'), { status: 403 })
  • Related