In some cases, when consuming external APIs, the inclusion of a
safe_decode method within ActiveSupport Core Extensions can prove to be a valuable addition.
External APIs can return data that may not necessarily be a well-formed JSON string; it may even come in the form of a plain text string. In such situations, safe_decode can gracefully handle the response without causing exceptions.
This is something I’ve had to handle in a production environment a number of times.
Following a similar approach to
safe_decode method can return nil if a ParserError is encountered.
def safe_decode(json) decode(json) rescue parse_error nil end
An alternative proposal would be returning the original string as follows:
def safe_decode(data) decode(data) rescue parse_error data end
This addition would not only facilitate handling APIs that return both plain text and JSON strings but also enable the reuse of HTTP client library classes designed to manage HTTP requests with multiple endpoints.
The purpose of
safe_decode is to handle such data without requiring you to manually preprocess it using
to_json to make it valid JSON.
Let me know if you think it’s a useful addition or if there is a better alternative (already in use). Happy to do the PR if there is positive feedback.