Assuming it's all about resending request to some buggy/bloat-up 3rd party API
If it's production question rather educational one I'd suggest search for 3rd party lib that implementing this on your own.
Say for axios
there is nice axios-retry
.
Why? Assume you may think there is just one case when API say returns 502. But actually there are much more cases it'd be better to keep in mind:
- differing particular error causes, say once there is Network or DNS Lookup Error there may be no need to repeat request
- retry count limitation
- increasing delay
- something else
Writing such a logic on your own would be real overkill. And trying to use simplest solution may hit you when you don't expect it.
PS also as a bonus you would be able to configure all requests to some specific API with single snippet like it goes for axios
' custom instances(and I believe there should other plugins for alternative libraries)