Skip to content

How to add a hook that always runs on success and failure? #212

@IGx89

Description

@IGx89

Hello! I really like this library you've come up with and am starting to convert a project over to it (from Axios). I've run into a use case however that I can't quite port. I have code that needs to run at the end of every request, that does different things based on whether an error was thrown or not. I thought middlewares would be the way to do so, however the middleware runs before the response is processed and the catchers are run. Scenarios where it breaks:

  • Response is not "ok" (could check for response.ok in the middleware, like the retry middleware does, but doesn't handle the 404 example below)
  • Response is not "ok" but the individual request has a notFound (for example) that swallows the exception and thus makes it effectively "ok".

One example use case is a middleware/addon that sets an error message/success message on the screen based on whether the request succeeded or not. I can't do that reliably currently, since there's no way to know for certain if an error was thrown or not. I could use catcherFallback to always know if an error was thrown (though there can only be one so that's not perfect), but I'd still have no way to run code when an error wasn't thrown.

Apologies if I'm not explaining things properly! I'm basically looking for a way to globally effectively add a .then and .catch onto every request call.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions