balena-io / balena-sdk

The SDK to make balena powered JavaScript applications.
https://www.balena.io/
Apache License 2.0
146 stars 46 forks source link

Pass request options to interceptor #1151

Open bartversluijs opened 3 years ago

bartversluijs commented 3 years ago

Hi all,

I'm trying to add a custom interceptor to the Balena request. Everything works as expected, however, only when a BalenaRequestError occurs, the Request Options are passed in the error.

I'm using the SDK to communicate to my openBalena instance, where I can only login using the credentials. But after 7 days, the token expires. I'm trying to fix this by adding an "error" interceptor, which handles errors when the authorization fails (like an Unauthorized response, or a Balena error: BalenaNotLoggedIn, BalenaExpiredToken or BalenaMalformedToken). But because the request options aren't passed with every error, I can't retry the request after I force reauthentication again.


I've already tested it by forcing a BalenaRequestError, which responds Unauthorized and retrying the request using:

sdk.request.send(error.requestOptions);

This works as expected, so it'd be awesome if I can also handle the rest of the errors by passing the request options to every error.

Thanks in advance!

thgreasi commented 3 years ago

Hi, Can you clarify whether you are using the requestError or the responseError interceptor? The reason only BalenaRequestError errors include the request options is that the rest of the errors you mentioned (eg responseError) are thrown during the normalization process of the request options. Would it be fine with you if we offered those options even in this uh/half-processed state?

bartversluijs commented 2 years ago

Hi @thgreasi,

First of all, sorry for my late response.

If I understand correctly, you're asking if it's fine to pass the request options with every error, even if the error occur'd before the request?

If so, yes. That would be ideal. The problem is I can't retry the request on a failure whatsoever. I'm using openBalena, where I have to use login via credentials. However, when the JWT token isn't valid anymore, it won't try to login again which I understand. But I can force the login again on that error and retry the request via the interceptors. But I don't know which request is being executed at time of error, because it's a global interceptor.

Next to that, for error logging, it's also handy to always know which requests triggered the error. Maybe in most cases you won't need it, but I think the more data you have while an error occurs, the better.

Let me know what you think!