HttpError handling
See original GitHub issueI have a situation where I need to discriminate between a HttpError
raised by Koa (or any middleware) as opposed to any other type of error raised by the application - the latter should never occur if everything is correct, however the former is expected.
At the moment, I have a block of code like so:
import createError from "http-errors"
export async function errorHandler(ctx, next) {
try {
await next()
} catch (err) {
if (err instanceof createError.HttpError)
// this type of error is expected, should produce minimal logging
else
// create an alert for this type of error, since it should never occur in normal operation
}
}
This works, but I don’t think it’s ideal. The issue is that my project does not depend on the http-errors
library directly; only in so far as these errors are raised by Koa when I call the throw
or assert
functions in a handler. I would prefer if I could handle this case by interacting with some aspect of Koa - if Koa delegates that to http-errors
or some other library, I think that should be an implementation detail for Koa rather than meaning I need to introduce a library for this into my code.
So, this leaves me with two questions:
- Is this the appropriate way to handle this situation, or is there some other mechanism I should be using?
- If this is the correct way to handle this case, can Koa export the errors in use from other libraries?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:2
- Comments:11 (6 by maintainers)
Top GitHub Comments
@jonathanong Because I have several different types of errors being created in different places, each contain a status code. I can potentially identify that an error is not type
A
orB
(where these are non-koa errors) by looking for discriminating properties, but this seems like a poor solution when I don’t care about discriminating between those types of error. I specifically care about the errors raised by koa and need to treat them separately.Landed https://github.com/koajs/koa/commit/2d1c5981869e0fe6f5bc71b5c5582accfd125cc6 released with Koa 2.9