Kevin Mistry in Development 2 minute read

Ionic: Handle Http Response Error Codes In Interceptor



While looking around on how to handle intercepting an http response and redirect for a 401 unauthorized, or displaying a popup for a 408 timeout, I found several different options. All of which seemed like over kill. Surely the framework had to be able to already handle this. After still not finding what I was looking for, I sat and thought about it. No Google, no assistance from the internets. Frequently unchartered territory in our line of work. After a couple of moments, I had a lightbulb moment. Just use the built-in events!

First, in the app.component I create my events to listen for. In my case, I have an unauthorized which will remove authentication and user data. This will then redirect to my login page and show a popup message indicating what happened. I also have an event that will listen for timeouts. You could just combine these into one event and dictate which logic branch to take by passing the response code. I register these events during the initialization of my app.component.

Next, we need to add ionic angular to our response interceptor by importing the events and implementing them in the constructor. As you can tell, I am using Angular Common HTTP. Finally, we must implement the logic which checks the status codes and handle the appropriate one. Below, I check for the Unauthorized and Timeout error codes. I also have an internal timeout that I am checking for. This is defined in my HTTP Interceptor for outgoing calls, which adds a reject after 15 seconds. From here, just call the appropriate event.

Viola, the magic happens. I have surprised myself lately with my ability to accomplish these tasks without the assistance of Google and/or smarter individuals who have ventured here before me. I may not be a smart man, but I do know what code is.