Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error Handling Utility: Simplify Asynchronous Code in JavaScript #136

Open
4 of 5 tasks
zeroqs opened this issue Dec 1, 2024 · 4 comments
Open
4 of 5 tasks

Error Handling Utility: Simplify Asynchronous Code in JavaScript #136

zeroqs opened this issue Dec 1, 2024 · 4 comments

Comments

@zeroqs
Copy link

zeroqs commented Dec 1, 2024

What is the feature?

This feature provides a utility function for JavaScript that simplifies asynchronous code handling by returning results and errors. Developers can easily manage success and failure cases without writing verbose try...catch blocks.

Example:

const [error, users] = await catchError(fetchUsers());

Why is this feature needed?

This feature introduces a clean, declarative way to manage errors, making the code more concise and easier to maintain.

Any additional comments?

No response

Confirmations

  • I have read the Code of Conduct
  • I have read the Issue Reporting Guidelines
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate
  • I know that any inappropriate content may cause the maintainer to take action base on the Code of Conduct
  • This feature request is open because to fix a bug/issue
@xiaodong2008
Copy link
Member

Thanks, that's a good idea really.

Btw, I think the code should be

const [error, users] = await catchError(fetchUsers);
// or
const [error, users] = await catchError(() => fetchUsers());

@xiaodong2008
Copy link
Member

xiaodong2008 commented Dec 3, 2024

What do you think of this implementation?

const users = await catchError(fetchUsers);
if (users instanceof Error) {}
else {}
// or
const [users, error] = await catchError(fetchUsers, true);

@zeroqs
Copy link
Author

zeroqs commented Dec 4, 2024

Hi,
I think the approach of

const users = await catchError(fetchUsers);

has some downsides. Specifically, checking for errors by testing if the result is an instance of Error feels less intuitive and introduces unnecessary complexity.

And in other cases, I think everything is fine

Only I didn't understand why true is the second argument :)

@xiaodong2008
Copy link
Member

The true means that catchError will return the result as an array: [res, error].

I think that providing both choices will be better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants