-
Notifications
You must be signed in to change notification settings - Fork 3
Reinforce api server fetch #225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
We should check the content type problem in the bff/ui-backend if we are setting the wrong content-type there |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR enhances the robustness of API response parsing by introducing a fallback mechanism that attempts to parse responses as JSON first, then falls back to text if JSON parsing fails. This addresses issues where valid JSON responses are served with incorrect Content-Type headers (e.g., "text/plain" instead of "application/json").
- Adds a new
parseJsonOrText
utility function that gracefully handles response parsing - Updates all response parsing locations to use the new fallback mechanism
- Improves error handling by ensuring error information is always captured regardless of response format
Yes, I have tried to distinguish data by Content Type but it not always correct. The issue should be gone with implementing GraphQL and generating types from it. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think I would agree with Copilot's suggestion regarding the typing. It wouldn't be ideal to assert the return type as T
when we're actually dealing with a string – that would just mask the real issue. When callers expect JSON data, returning a plain string would just cause confusing errors down the line. In this case, it makes more sense to let the JSON conversion throw an error (nothing is gained by the conversion to text). So, for the happy path where everything works as expected, I think we should keep it simple and return res.json()
.
There was a previous case where fetch failed (!res.ok
) and returned an error as plain text, but we tried parsing it as JSON to get the error details. For error scenarios like this, parsing as text might be sensible.
What are your thoughts? We can also discuss it in a call, I think when it comes to error handling we have some todos anyway 🙂
What this PR does / why we need it:
Added try/catch to parse response into JS object when it is a correct response, if no then parse it as a string.
I was unable to use Content-Type to distinguish it because sometimes correct JSON comes as a content-type: text/plain; charset=utf-8 type.