JS-DevTools / ono

Wrap errors without losing the original message, stack trace, or properties
https://jstools.dev/ono/
MIT License
106 stars 11 forks source link

Wrap an error preserving the prototype of the base error? #12

Closed ryanleecode closed 4 years ago

ryanleecode commented 4 years ago

Is there a way to wrap an error so that the instance/prototype of the original error is not lost? This makes it easy to catch up the stack using instanceof calls or decorators that rely on using the class constructor.

JamesMessinger commented 4 years ago

The default ono() function does that. If the first argument is an instance of Error (or any inherited type), then it will create an instance of the same class. You can also use this with your own custom error classes as well

ryanleecode commented 4 years ago

Can you look at this codesandbox?

https://codesandbox.io/s/peaceful-tesla-fxy31?fontsize=14&hidenavigation=1&theme=dark

JamesMessinger commented 4 years ago

@ryanleecode Thanks for sending a code sample. You were just missing one line, which registers your custom error type with Ono:

ono.myError = new Ono(MyError);

Here's a complete working demo

ryanleecode commented 4 years ago

Is there a way to do this elegantly in typescript without having to extend the .d.ts file?

JamesMessinger commented 4 years ago

Not that I'm aware of. But perhaps someone who's more of a TypeScript pro will know a way