Skip to content

Instantly share code, notes, and snippets.

@craigphicks
Last active August 12, 2019 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigphicks/4a01343a6a80a3b624b136b99397964a to your computer and use it in GitHub Desktop.
Save craigphicks/4a01343a6a80a3b624b136b99397964a to your computer and use it in GitHub Desktop.
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