Handle API Errors in vue spa
2 min readMar 8, 2021
Talking to an API you can have a multitude of errors. Some of which you most likely always want to handle in your pages/components? How do you handle them?
I’ve recently had a think about this, after reading/watching about hexagonal architecture, as well as working with Elixir. I think I came up with a nice solution. So I’ll share it here.
The basic premise is you never call Axios/Fetch directly. you always use your own wrapper, in my case I call this HTTP
it looks something like this:
There are most likely better ways to handle this, but I like this solution. Basically what you get when using this are several benefits:
- I could replace Axios with Fetch or any other way of fetching data and the spa couldn’t care less about it, and if you write your tests with MSWjs (consider doing it) the tests won’t have to change.
- The HTTP module only throws on truly unexpected/unhandled cases. otherwise, it returns a
{state,data}
object which you can handle in your Component/Vuex. This means that you don’t have totry/catch
, to check if you got a 404 or 500 error. You simply handle the cases that are expected,server_error/not_found/validation_error/unauthorised/etc.
So when using the HTTP module, it always makes you think about how to handle the expected cases for your API.