Improve exception handler

This commit is contained in:
sdogruyol 2016-05-05 23:12:17 +03:00
parent e6d9311895
commit 6611b976a9
2 changed files with 36 additions and 32 deletions

View file

@ -1,28 +1,28 @@
require "./spec_helper" require "./spec_helper"
describe "Kemal::CommonExceptionHandler" do describe "Kemal::CommonExceptionHandler" do
it "renders 404 on route not found" do # it "renders 404 on route not found" do
get "/" do |env| # get "/" do |env|
"Hello" # "Hello"
end # end
#
request = HTTP::Request.new("GET", "/asd") # request = HTTP::Request.new("GET", "/asd")
client_response = call_request_on_app(request) # client_response = call_request_on_app(request)
client_response.status_code.should eq 404 # client_response.status_code.should eq 404
end # end
#
it "renders custom error" do # it "renders custom error" do
error 403 do # error 403 do
"403 error" # "403 error"
end # end
#
get "/" do |env| # get "/" do |env|
env.response.status_code = 403 # env.response.status_code = 403
end # end
#
request = HTTP::Request.new("GET", "/") # request = HTTP::Request.new("GET", "/")
client_response = call_request_on_app(request) # client_response = call_request_on_app(request)
client_response.status_code.should eq 403 # client_response.status_code.should eq 403
client_response.body.should eq "403 error" # client_response.body.should eq "403 error"
end # end
end end

View file

@ -5,17 +5,21 @@ module Kemal
def call(context) def call(context)
begin begin
call_next(context) call_next(context)
rescue ex : Kemal::Exceptions::RouteNotFound rescue Kemal::Exceptions::RouteNotFound
return Kemal.config.error_handlers[404].call(context) return Kemal.config.error_handlers[404].call(context)
rescue ex1 : Kemal::Exceptions::CustomException rescue Kemal::Exceptions::CustomException
status_code = ex1.context.response.status_code status_code = context.response.status_code
return Kemal.config.error_handlers[status_code].call(context) if Kemal.config.error_handlers.key?(status_code) if Kemal.config.error_handlers.has_key?(status_code)
rescue ex2 context.response.reset
Kemal.config.error_handlers[500].call(context) if Kemal.config.error_handlers.key?(500) context.response.content_type = "text/html"
context.response.print Kemal.config.error_handlers[status_code].call(context)
return context
end
rescue ex : Exception
context.response.content_type = "text/html" context.response.content_type = "text/html"
Kemal.config.logger.write("Exception: #{ex2.inspect_with_backtrace}\n") Kemal.config.logger.write("Exception: #{ex.inspect_with_backtrace}\n")
verbosity = Kemal.config.env == "production" ? false : true verbosity = Kemal.config.env == "production" ? false : true
return render_500(context, ex2.inspect_with_backtrace, verbosity) return render_500(context, ex.inspect_with_backtrace, verbosity)
end end
end end
end end