Skip to content

Commit

Permalink
Define subclass of Goliath::Validation::Error for each standard HTTP …
Browse files Browse the repository at this point in the history
…error code (4xx and 5xx): Goliath::Validation::NotFoundError, Goliath::Validation::GatewayTimeoutError, and so forth.
  • Loading branch information
Philip (flip) Kromer committed Apr 18, 2011
1 parent 57c5ae1 commit 405e5a8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/goliath/validation/standard_http_errors.rb
@@ -0,0 +1,23 @@
module Goliath
#
# Make a subclass of Goliath::Validation::Error for each standard HTTP error
# code (4xx and 5xx). Error will have a default status_code and message
# correct for that response:
#
# err = Goliath::Validation::NotFoundError.new
# p [err.status_code, err.to_s]
# # => [400, "Not Found"]
#
# Each class is named for the standard HTTP message, so 504 'Gateway Time-out'
# becomes a Goliath::Validation::GatewayTimeoutError. All non-alphanumeric
# characters are smushed together, with no upcasing or downcasing.
#

HTTP_ERROR_CODES = HTTP_STATUS_CODES.select{|code,msg| code >= 400 && code <= 599 }
HTTP_ERROR_CODES.each do |code, msg|
klass_name = msg.gsub(/\W+/, '')+'Error'
klass = Class.new(Goliath::Validation::Error)
klass.class_eval %Q{def initialize(status_code='#{code}', message='#{msg}') super(status_code, message) ; end }, __FILE__, __LINE__
Goliath::Validation.const_set klass_name, klass
end
end
16 changes: 16 additions & 0 deletions spec/unit/validation/standard_http_errors_spec.rb
@@ -0,0 +1,16 @@
require 'spec_helper'
require 'goliath/rack/validation_error'
require 'goliath/validation/standard_http_errors'

describe Goliath::Validation::Error do
it 'defines exceptions for each standard error response' do
lambda { Goliath::Validation::BadRequestError.new }.should_not raise_error
Goliath::Validation::BadRequestError.should < Goliath::Validation::Error
end

it 'sets a default status code and message' do
Goliath::Validation::NotFoundError.new.status_code.should == '404'
Goliath::Validation::NotFoundError.new.message.should == 'Not Found'
end
end

0 comments on commit 405e5a8

Please sign in to comment.