Permalink
Browse files

Merge remote-tracking branch 'eac/eac/exception_handling'

  • Loading branch information...
2 parents fecfbc5 + 49cd3bc commit 4aca5c9c2a03085a443887221e79b870839001c5 @jeremy committed May 30, 2012
Showing with 55 additions and 0 deletions.
  1. +24 −0 lib/statsd.rb
  2. +6 −0 spec/helper.rb
  3. +25 −0 spec/statsd_spec.rb
View
@@ -14,6 +14,30 @@
# statsd = Statsd.new('localhost').tap{|sd| sd.namespace = 'account'}
# statsd.increment 'activate'
class Statsd
+ # Don't raise exceptions when collection fails.
+ # If a logger is provided, the exception will be logged.
+ #
+ # @example
+ # Statsd.logger = Logger.new(STDOUT)
+ # statsd = Statsd.new
+ # statsd.extend(Statsd::ExceptionHandling)
+ module ExceptionHandling
+
+ attr_accessor :logger
+
+ def send(*args)
+ super
+ rescue Exception => exception
+ logger.error("Statsd: #{exception}") if logger
+ false
+ end
+
+ def logger
+ @logger ||= self.class.logger
+ end
+
+ end
+
# A namespace to prepend to all statsd calls.
attr_reader :namespace
View
@@ -24,6 +24,12 @@ def recv
res = @buffer.shift
end
+ def break!
+ instance_eval do
+ def send(message, *rest); raise SocketError end
+ end
+ end
+
def clear
@buffer = []
end
View
@@ -13,6 +13,31 @@ class Statsd
after { @statsd.socket.clear }
+ describe "Exception handling" do
+ before do
+ @statsd.extend(Statsd::ExceptionHandling)
+ end
+
+ it "should send messages when there are no exceptions" do
+ @statsd.increment('foobar')
+ @statsd.socket.recv.must_equal ['foobar:1|c']
+ end
+
+ it "should fail silently when encountering an error on send" do
+ @statsd.socket.break!
+ assert_equal false, @statsd.increment('foobar')
+ end
+
+ it "should log the exception when a logger is provided" do
+ @statsd.socket.break!
+ log = StringIO.new
+ @statsd.logger = Logger.new(log)
+
+ @statsd.increment('foobar')
+ log.string.must_match 'Statsd: SocketError'
+ end
+ end
+
describe "#initialize" do
it "should set the host and port" do
@statsd.host.must_equal 'localhost'

0 comments on commit 4aca5c9

Please sign in to comment.