workos / workos-node

Official Node SDK for interacting with the WorkOS API
https://workos.com/docs/sdk/node
MIT License
116 stars 28 forks source link

Types for errors #959

Open samuelgozi opened 7 months ago

samuelgozi commented 7 months ago

It seems like when the internal works api (api.workos.com) throws an error you just return it. For example the api authenticateWithCode can throw an error for email verification, but the types for the errors are not in this library.

Can you guys please add a custom error type and interfaces for your errors?

Here is how I need to handle it now:

workos.userManagement.authenticateWithCode({ clientId, code }).catch((error) => {
    // The error code should be as described here:
    // https://workos.com/docs/reference/user-management/authentication-errors
    if (error.code === "email_verification_required") {
        context.set.status = 401; // unauthorized
        return error;
    }

    // Additional if clauses for other errors.

    // Else let the error bubble up
    throw error;
});

Now I have two problems, a) my API is not typed unless I create types for all the errors manually, and b) I need to write code to handle all the workOS errors to separate them from server errors, as can be seen I the if clause.

If you were to use custom error classes then problem "a" would be solved, and if you add types then problem "b" would be solved. Or better yet you could create both and type the classes so that we get the best of bth worlds.

My code would then look like this:

workos.userManagement.authenticateWithCode({ clientId, code }).catch((error) => {
    if (error instanceof AuthenticationError) {
        // handle works errors
    }

    // Else let the error bubble up
    throw error;
});

And the error will be typed!

isaachinman commented 1 month ago

@PaulAsjes @mthadley @mattgd

Just found this issue, as I ran into the same problem myself. I would strongly suggest you export a WorkOS.APIError enum, or something similar.

Or, if you don't want to provide an enum, at least provide a type.

Your customers need to be able to build downstream behaviour based on thrown errors.