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

Add support for custom errors #6

Closed wrumsby closed 5 years ago

wrumsby commented 5 years ago

This change fixes #4.

I wasn't quite able to provide the API suggested in #4, but instead added a custom method with tests, type definitions and documentation in README.md.

coveralls commented 5 years ago

Pull Request Test Coverage Report for Build 135


Changes Missing Coverage Covered Lines Changed/Added Lines %
lib/ono.js 8 9 88.89%
<!-- Total: 8 9 88.89% -->
Files with Coverage Reduction New Missed Lines %
lib/ono.js 9 96.08%
<!-- Total: 9 -->
Totals Coverage Status
Change from base Build 133: -8.9%
Covered Lines: 87
Relevant Lines: 99

💛 - Coveralls
JamesMessinger commented 5 years ago

Thanks for the PR! I'll review it soon and get it merged.

wrumsby commented 5 years ago

Thanks for the PR! I'll review it soon and get it merged.

@JamesMessinger I know I'm not completely following code style here - if you can point me in the right direction I'm happy to make changes.

JamesMessinger commented 5 years ago

@wrumsby - The PR looks great, but I see that you implemented the first of the two syntax options that I proposed in Issue #4, whereas I think the second syntax option is better because it's less verbose and repetitive. Basically, I'd like people to be able to add their own custom methods to ono, and then use those methods just like any of the built-in methods.

// Define your own custom error classes
class LoginError extends Error { ... }
class FileAccessError extends Error { ... }

// Create custom ono methods for your error classes
ono.login= new ono(LoginError);
ono.fileAccess = new ono(FileAccessError);

//  Use your custom ono methods just like any of the built-in methods
ono.login({ username, password }, "Invalid username or password");
ono.fileAccess(err, { username, filePath }, "User %s does not have access to file %s", username, filePath);
wrumsby commented 5 years ago

Hi @JamesMessinger right - that makes things clearer for me.

One thing I've been thinking about, but not really tried yet, is how this will work with TypeScript.

I know, for instance, Hapi has plugins and the type definitions for those plugins add the appropriate methods onto standard Hapi objects (I'm not sure how ATM). This made me wonder if an API like:

class LoginError extends Error { ... }

ono.register('login', LoginError);

...

ono.login(...);

might be needed or might be clearer. I'll try to look into this over the next few weeks and see what I can find.

JamesMessinger commented 5 years ago

We just released Ono v5.0, which includes support for custom errors. This PR inspired it, so thank you!

Here are the release notes