diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 97777788..86da7e11 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -609,6 +609,11 @@ module Sinatra status == 404 end + # whether or not the status is set to 400 + def bad_request? + status == 400 + end + # Generates a Time object from the given value. # Used by #expires and #last_modified. def time_for(value) @@ -1133,12 +1138,15 @@ module Sinatra status(500) unless status.between? 400, 599 + boom_message = boom.message if boom.message && boom.message != boom.class.name if server_error? dump_errors! boom if settings.dump_errors? raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler elsif not_found? headers['X-Cascade'] = 'pass' if settings.x_cascade? - body '

Not Found

' + body boom_message || '

Not Found

' + elsif bad_request? + body boom_message || '

Bad Request

' end res = error_block!(boom.class, boom) || error_block!(status, boom) diff --git a/test/helpers_test.rb b/test/helpers_test.rb index 48e79066..d8f65ddc 100644 --- a/test/helpers_test.rb +++ b/test/helpers_test.rb @@ -26,6 +26,23 @@ class HelpersTest < Minitest::Test end end + describe 'bad_request?' do + it 'is true for status == 400' do + status_app(400) { bad_request? } + assert_body 'true' + end + + it 'is false for status gt 400' do + status_app(401) { bad_request? } + assert_body 'false' + end + + it 'is false for status lt 400' do + status_app(399) { bad_request? } + assert_body 'false' + end + end + describe 'not_found?' do it 'is true for status == 404' do status_app(404) { not_found? } diff --git a/test/routing_test.rb b/test/routing_test.rb index 0dcae602..7bab661f 100644 --- a/test/routing_test.rb +++ b/test/routing_test.rb @@ -54,7 +54,7 @@ class RoutingTest < Minitest::Test request = Rack::MockRequest.new(@app) response = request.request('GET', '/foo?bar=&bar[]=', {}) - assert_equal 400, response.status + assert response.bad_request? end it "404s when no route satisfies the request" do @@ -175,6 +175,32 @@ class RoutingTest < Minitest::Test assert_equal 404, status end + it "captures the exception message of a raised NotFound" do + mock_app { + get '/' do + raise Sinatra::NotFound, "This is not a drill" + end + } + + get "/" + assert_equal "19", response["Content-Length"] + assert_equal 404, status + assert_equal "This is not a drill", response.body + end + + it "captures the exception message of a raised BadRequest" do + mock_app { + get '/' do + raise Sinatra::BadRequest, "This is not a drill either" + end + } + + get "/" + assert_equal "26", response["Content-Length"] + assert_equal 400, status + assert_equal "This is not a drill either", response.body + end + it "uses 404 error handler for not matching route" do mock_app { not_found do