-
Notifications
You must be signed in to change notification settings - Fork 1
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
Using custom Error types for consistency and brevity in error status codes #5
Comments
I've seen in a new branch by @msanroman we often duplicate a ton of code in each RPC handler: if (!accountId) {
throw createError({
message: 'accountId must be specified',
code: REQUIRED_PARAMETER_MISSING,
})
} Which could be shortened by 3 lines of code and make it be much easier to read! if (!accountId) {
throw MissingParameterError('accountId')
} If we wanted to add another separate library or some utils with this library, we could do things like this: // Potential rpc library util function
const requireParameters = (obj) => {
for (let key of obj) {
if (!obj[key]) throw MissingParameterError(key)
}
}
// Example rpc handler in a service:
const getChannelsForProduct = async ({ accountId, product }) => {
requireParameters({ accountId, product }) // will throw if one is undefined
// do business logic
} |
That's a really great idea @djfarrelly ! 🙌 I wonder if this pattern could be used across rpc & http or functions in code , we often need to verify missing parameters and throw errors. |
I love it! 👍 |
I agree this would be a great improvement. I specially like the idea of allowing consumers of an RPC server to use the exported types to be able to understand errors better. When thinking about defining new error types, I would suggest we take inspiration from (or even depend on) verror which offers quite a nice interface to chain errors. Our apps usually have a pattern of:
So |
Copied from bufferapp/micro-rpc#2
Purpose
Inspired by Apollo server's way to throw errors, I was thinking it might be a little nicer than the current
createError
pattern.Proposal
Instead of creating the error and optionally pass an error code, we have specific errors that consumers can import which might make things consistent.
These errors would already have the err.statusCode set.
This also could help us remove this library's dependency on
micro
or we could use this pattern to create a newmicro
-less rpc library since we're using Express under the hood.The text was updated successfully, but these errors were encountered: