moll / js-standard-error

Tiny JavaScript library that simplifies subclassing and inheriting from Error while keeping the correct name and stack. Also supports constructing from an object of properties. Saves you from boilerplate.
Other
42 stars 2 forks source link

StandardError constructor with Error instance parameter #2

Closed chaudhryjunaid closed 8 years ago

chaudhryjunaid commented 9 years ago

What would I have to do to convert a javascript Error instance to a StandardError instance keeping the same message and stack trace? I don't want to manually put in values of message etc. Would a StandardError constructor that takes Error instance as a parameter help?

Any advice would be much appreciated! Thanks!

moll commented 9 years ago

Hey!

Any particular reason you want to do that? Wish to whitelist and wrap some Errors to StandardError so err instanceof StandardError would continue to work somewhere down the line?

chaudhryjunaid commented 9 years ago

Yep! Exactly! Also, to make the message property of the error printable and retain the same stack as the original Error. My problem is throwing a new StandardError loses the original error stack. Appreciate your prompt response.

(I am currently working out a way to streamline errors in my express app so that I can dispense entirely with the Error object by casting every interesting Error to StandardError and letting only the boring / really unexpected ones fall to the last handler.)

chaudhryjunaid commented 8 years ago

I have figured out a solution. I am attaching the original error as a property of the new Standard Error.

moll commented 8 years ago

Hey again! Thanks for following up and my bad for the radio silence. Too many things, too little time. Anywho, I wasn't necessarily against somehow merging-replacing an existing error, though I don't know what the best way to approach it would be.

Acting as if the StandardError came from where the original error was craeted might be a misleading: When you go to look at the code in the trace, it'll be mentioning some other error class. :) I've so far done what you did: assign the other error as a property, though then you do have to show the stack manually in your error reporting code.

One hack you could do in your subclass of StandardError would be to define a stack getter on its prototype that then returns the stack of your nested error. StandardError's constructor should be smart enough to not overwrite that getter.