From 525d99f1421c54844ebe13cb4a3d0480feab17a1 Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Thu, 29 Nov 2007 17:56:18 -0800 Subject: [PATCH] Custom 500's --- lib/sinatra.rb | 41 +++++++++++++++++++++++++++------------ test/custom_error_test.rb | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 12 deletions(-) create mode 100644 test/custom_error_test.rb diff --git a/lib/sinatra.rb b/lib/sinatra.rb index a52eedc..3fb90a6 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -258,27 +258,44 @@ module Sinatra '

Not Found

' end end + + def basic_error + Error.new(500) do + '

Internal Server Error

' + end + end def options @options ||= OpenStruct.new(default_options) end def call(env) - result = lookup(env) - context = EventContext.new( - Rack::Request.new(env), - Rack::Response.new, - result.params - ) - context.status(result.status) - returned = catch(:halt) do - [:complete, context.instance_eval(&result.block)] + body = nil + begin + result = lookup(env) + context = EventContext.new( + Rack::Request.new(env), + Rack::Response.new, + result.params + ) + context.status(result.status) + returned = catch(:halt) do + [:complete, context.instance_eval(&result.block)] + end + body = returned.to_result(context) + rescue => e + env['sinatra.error'] = e + result = (events[:errors][500] || basic_error).invoke(env) + returned = catch(:halt) do + [:complete, context.instance_eval(&result.block)] + end + body = returned.to_result(context) + context.status(500) end - result = returned.to_result(context) - context.body = String === result ? [*result] : result + context.body = String === body ? [*body] : body context.finish end - + end end diff --git a/test/custom_error_test.rb b/test/custom_error_test.rb new file mode 100644 index 0000000..6bd3f3e --- /dev/null +++ b/test/custom_error_test.rb @@ -0,0 +1,49 @@ +require File.dirname(__FILE__) + '/helper' + +context "Custom Errors (in general)" do + + specify "override the default 404" do + + get_it '/' + should.be.not_found + body.should.equal '

Not Found

' + + error 404 do + 'Custom 404' + end + + get_it '/' + should.be.not_found + body.should.equal 'Custom 404' + + end + + specify "override the default 500" do + + get '/' do + raise 'asdf' + end + + get_it '/' + status.should.equal 500 + body.should.equal '

Internal Server Error

' + + + error 500 do + 'Custom 500 for ' + request.env['sinatra.error'].message + end + + get_it '/' + + get_it '/' + status.should.equal 500 + body.should.equal 'Custom 500 for asdf' + + end + +end + + + + + -- 2.11.4.GIT