Skip to content

Include response object in error when response is HTML and there is JSON::ParserError exception #324

@marisveide

Description

@marisveide

Steps to reproduce:

  1. Make a REST API endpoint which supposedly fails, and returns HTML response (instead of JSON). Add a rescue block to catch all errors and get the error object from it.
  2. Make the request with ActiveResource to that REST API endpoint.
  3. See that the request blows up with an exception JSON::ParserError.
  4. See that in the error object in the rescue block doesn't have a response attribute.

Expected result:

The error object should ideally have the request and response objects attributes, so that we can log them, and properly react to such cases depending on the request and response attributes, headers, etc.

Code place where the issue is:

It's in file:
https://github.com/rails/activeresource/blob/master/lib/active_resource/base.rb

This code fragment:

        # Find every resource
        def find_every(options)
          begin
            case from = options[:from]
            when Symbol
              instantiate_collection(get(from, options[:params]), options[:params])
            when String
              path = "#{from}#{query_string(options[:params])}"
              instantiate_collection(format.decode(connection.get(path, headers).body) || [], options[:params])
            else
              prefix_options, query_options = split_options(options[:params])
              path = collection_path(prefix_options, query_options)
              instantiate_collection((format.decode(connection.get(path, headers).body) || []), query_options, prefix_options)
            end
          rescue ActiveResource::ResourceNotFound
            # Swallowing ResourceNotFound exceptions and return nil - as per
            # ActiveRecord.
            nil
          end
        end

This call fails:

format.decode(connection.get(path, headers).body

The call is chained, so the request and response objects are not captured to a raised error, and cannot be accessed if format.decode raises an exception.

Suggested solution:

module ActiveResource

  class ResponseError < StandardError
    attr_reader :response

    def initialize(response, message = nil)
      @response = response
      @message = message
    end

    def to_s
      @message
    end
  end

end

Raise the ResponseError when there is an error parsing response JSON.

Would be really valuable if this can be solved.

Thanks so much!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions