2008-06-11 12:31:39 -07:00
|
|
|
require 'rexml/document'
|
|
|
|
|
|
|
|
module RestClient
|
|
|
|
# A redirect was encountered; caught by execute to retry with the new url.
|
|
|
|
class Redirect < RuntimeError; end
|
|
|
|
|
|
|
|
# Authorization is required to access the resource specified.
|
|
|
|
class Unauthorized < RuntimeError; end
|
|
|
|
|
2008-06-24 03:27:21 -07:00
|
|
|
# No resource was found at the given URL.
|
|
|
|
class ResourceNotFound < RuntimeError; end
|
|
|
|
|
2008-06-20 20:28:19 -07:00
|
|
|
# The server broke the connection prior to the request completing.
|
|
|
|
class ServerBrokeConnection < RuntimeError; end
|
|
|
|
|
2008-06-20 20:39:13 -07:00
|
|
|
# The server took too long to respond.
|
|
|
|
class RequestTimeout < RuntimeError; end
|
|
|
|
|
2008-06-20 19:09:57 -07:00
|
|
|
# The request failed, meaning the remote HTTP server returned a code other
|
|
|
|
# than success, unauthorized, or redirect.
|
|
|
|
#
|
|
|
|
# The exception message attempts to extract the error from the XML, using
|
|
|
|
# format returned by Rails: <errors><error>some message</error></errors>
|
|
|
|
#
|
|
|
|
# You can get the status code by e.http_code, or see anything about the
|
|
|
|
# response via e.response. For example, the entire result body (which is
|
|
|
|
# probably an HTML error page) is e.response.body.
|
2008-06-11 12:31:39 -07:00
|
|
|
class RequestFailed < RuntimeError
|
|
|
|
attr_accessor :response
|
|
|
|
|
2008-06-23 13:51:42 -07:00
|
|
|
def initialize(response=nil)
|
2008-06-11 12:31:39 -07:00
|
|
|
@response = response
|
|
|
|
end
|
|
|
|
|
|
|
|
def http_code
|
2008-06-23 13:51:42 -07:00
|
|
|
@response.code.to_i if @response
|
2008-06-11 12:31:39 -07:00
|
|
|
end
|
|
|
|
|
2008-06-20 19:22:19 -07:00
|
|
|
def message(default="Unknown error, HTTP status code #{http_code}")
|
2008-06-23 13:51:42 -07:00
|
|
|
return default unless @response
|
2008-06-11 15:08:31 -07:00
|
|
|
parse_error_xml rescue default
|
2008-06-11 12:31:39 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def parse_error_xml
|
|
|
|
xml_errors = REXML::Document.new(@response.body).elements.to_a("//errors/error")
|
|
|
|
xml_errors.empty? ? raise : xml_errors.map { |a| a.text }.join(" / ")
|
|
|
|
end
|
2008-06-20 19:22:19 -07:00
|
|
|
|
|
|
|
def to_s
|
|
|
|
message
|
|
|
|
end
|
2008-06-11 12:31:39 -07:00
|
|
|
end
|
2008-06-12 11:21:39 -07:00
|
|
|
end
|
|
|
|
|
2008-06-20 19:09:57 -07:00
|
|
|
# backwards compatibility
|
2008-06-23 13:50:08 -07:00
|
|
|
class RestClient::Request
|
|
|
|
Redirect = RestClient::Redirect
|
|
|
|
Unauthorized = RestClient::Unauthorized
|
|
|
|
RequestFailed = RestClient::RequestFailed
|
|
|
|
end
|