Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Raise ApiError if API request failed

  • Loading branch information...
commit 0037c0f1b28aa61ce7292578675fcf46f10b0285 1 parent a1a4944
Kirill Lashuk KL-7 authored committed
15 lib/scrobbler/base.rb
View
@@ -13,6 +13,8 @@
module Scrobbler
API_URL = 'http://ws.audioscrobbler.com/' unless defined? API_URL
+
+ class ApiError < StandardError; end
class Base
@@ -185,12 +187,25 @@ def Base.request(api_method, parameters = {}, request_method = 'get')
xml = fetch_http(request_method, paramlist) if xml.nil?
# Process it
doc = Nokogiri::XML(xml) { |config| config.noent.noblanks.nonet }
+ # Validate it
+ validate_response_document doc
# Write to cache
save_to_cache(xml, parameters) if check_cache
# Return the parsed result
doc
end
+
+ # Check response status, raise ApiError if request failed.
+ #
+ # @param [Nokogiri::XML::Document] document Response XML document.
+ # @return [void]
+ def Base.validate_response_document(document)
+ unless document.root and document.root['status'] == 'ok'
+ error_message = (document.content if document.root.child.name == 'error') rescue nil
+ raise ApiError, error_message
+ end
+ end
# Load information into instance variables.
#
4 test/fixtures/xml/base/invalid_api_key.xml
View
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<lfm status="failed">
+ <error code="10">Invalid API key - You must be granted a valid key by last.fm</error>
+</lfm>
6 test/mocks/rest.rb
View
@@ -15,6 +15,10 @@ def register_fw(uri, *args)
## Library
require File.expand_path('library.rb', File.dirname(__FILE__))
+## Base
+register_fw('user=invalid_api_key&api_key=foo123&method=user.getinfo',
+ 'base', 'invalid_api_key.xml')
+
## Event
register_fw('method=event.getattendees&event=328799&api_key=foo123',
'event', 'attendees.xml')
@@ -113,7 +117,7 @@ def register_fw(uri, *args)
'user', 'lovedtracks.xml')
register_fw('user=jnunemaker&api_key=foo123&method=user.getinfo',
'user', 'info.xml')
-
+
# Album
register_fw('artist=Carrie%20Underwood&album=Some%20Hearts&api_key=foo123&method=album.getinfo',
'album', 'info.xml')
11 test/unit/base_spec.rb
View
@@ -0,0 +1,11 @@
+require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')
+
+describe Scrobbler::Base do
+
+ it "should raise exception if API error occures" do
+ lambda {
+ Scrobbler::Base.request 'user.getinfo', :user => 'invalid_api_key'
+ }.should raise_error(Scrobbler::ApiError, 'Invalid API key - You must be granted a valid key by last.fm')
+ end
+
+end
Please sign in to comment.
Something went wrong with that request. Please try again.