ky: Pass `TimeoutError`s to `beforeError` hooks
As of now, the beforeError hook only handles HTTPErrors. A hook for handling errors like TimeoutError would be beneficial to avoid having to wrap every request call in try { ... } catch { ... } blocks
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 15
- Comments: 24 (5 by maintainers)
We now have a handy entry point to handle any errors in our app. When an error occurs, we’ll show a friendly notification letting you know what went wrong. So, if I add a new API endpoint, I won’t need to add this part of the functionality explicitly. How I’ll manage the error in the try-catch block is the second question.
At the moment I have to add this duplicating logic to ALL(!) API calls in every try-catch.
As I see it, there are really two issues at play here.
beforeErrordoesn’t listen for all error types.try/catcheach Ky call individually.I think the main problem is
2. I would recommend that you call Ky without a localtry/catch. Let the errors bubble up. You can handle them in a centralized manner by using something like a React Error Boundary. On the server, hapi.js for example will automatically catch any errors thrown by route handlers, so if Ky throws in a route, it will automatically return a 500 error and there are hooks in hapi to modify how it handles those errors. If you’re using another framework, worst case scenario you could useprocess.on('uncaughtException', ...). The point is, find a good boundary where you can handle errors.I think of
beforeErroras just a place to make quick little modifications to HTTP error messages or whatever, in an app where more comprehensive error handling is not necessary. That said, I would support givingbeforeErrormore errors.Not within hooks. For now, if you want to handle network errors, you will need to wrap the request in a try catch.
Making
beforeErrormore comprehensive is definitely something we want to do. PRs welcome.If we do decide to do this, it should be named
beforeTimeout.Basically the intent is to have a centralized way to handle errors like
TimeoutErrorso that we don’t have to run atry...catchfor every call while still leveraging the Ky instance.“Just out of curiosity, if it would receive TimeoutError, what would you do with it in the hook?” Primarily communicating that a timeout error has occurred to the user in the UI, amongst other things
That would be great if you will add such hook. Could be very useful in some cases like the one above.
How about adding a separate
beforeTimeoutErrorfrombeforeError?Usage
My patch
Lets imagine that Ky supported this. What would happen on error? You handle the error in
beforeError, but theawait ky()call needs to resolve somehow. You don’t want it to throw, but it cannot resolve to a successful response either.