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

Custom Error #4

Closed pedro-mass closed 5 years ago

pedro-mass commented 6 years ago

I've started to incorporate ono for error handling, and for most cases it seems good.

I have some custom error types that I created and use for handling specific scenarios. How can I use ono to handle these custom types.

The docs have some defined types, but I'd like to be able to include some of my own.

JamesMessinger commented 6 years ago

The built-in error types in Ono correspond to the standard JavaScript error types. I hadn't considered supporting custom error types, but I think it's totally reasonable to add that functionality.

The catch is that you would have to specify the constructor somehow. One way to do that could be as a parameter to each ono call, like this:

throw ono(MyCustomError, "Something went wrong");
throw ono(MyCustomError, { status: 500 }, "Something went wrong");
throw ono(MyCustomError, err, { status: 500 }, "Something went wrong");

But that's probably too verbose and repetitive. So perhaps a better way would be to initialize a custom instance of ono with your custom error type, and then re-use that custom ono instance, like this:

var myOno = new ono(MyCustomError);

throw myOno("Something went wrong");
throw myOno({ status: 500 }, "Something went wrong");
throw myOno(err, { status: 500 }, "Something went wrong");
pedro-mass commented 6 years ago

That would be fantastic. I think the second approach would be cleaner for the existing interface.

JamesMessinger commented 5 years ago

We just released Ono v5.0, which includes support for custom error classes.

Here are the release notes