Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to extend error when prepending a message to an existing error which may or may not be instance of Error
function showDeep(t){
let o=t
do {
console.log(`--- ${o.constructor.name}`)
for (let k of Reflect.ownKeys(o)) {
let d = Reflect.getOwnPropertyDescriptor(o,k)
if (JSON.stringify(d.value)!==undefined) {
console.log(`${k} : ${JSON.stringify(d.value)}`)
if (k==='stack')
console.log("") // funky
}
}
} while (o=Reflect.getPrototypeOf(o))
}
class X extends Error {
constructor(m,e=null) {
let prev_stack=null
let msg = m
if (e instanceof Error) {
msg += ", " + e.message
prev_stack=e.stack
} else {
if (e && JSON.stringify(e)!==undefined) {
msg += ", " + JSON.stringify(e)
}
}
super(msg)
// her do something e.stack and this.stack if desired
if (prev_stack)
this.stack += '\n' + prev_stack
this.name=this.constructor.name
}
}
class Y extends X {
constructor(m,e){
super(m,e)
}
}
console.log("~~~~~~~~~~~~~~~~~~~~ new Error('help')")
let e = new Error('help')
//e.stack="original e stack" // this will be lost
showDeep(e)
console.log("~~~~~~~~~~~~~~~~~~~~ new Y('y')")
let y = new Y("y")
showDeep(y)
console.log("~~~~~~~~~~~~~~~~~~~~ new Y('y',e)")
let ye = new Y("y",e)
showDeep(ye)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.