kemal/src/kemal/common_exception_handler.cr

31 lines
1.2 KiB
Crystal
Raw Normal View History

2016-05-05 19:35:36 +00:00
module Kemal
2016-07-17 11:26:22 +00:00
# Kemal::CommonExceptionHandler handles all the exceptions including 404, custom errors and 500.
2016-05-05 19:35:36 +00:00
class CommonExceptionHandler < HTTP::Handler
INSTANCE = new
2016-02-14 10:43:25 +00:00
2016-05-05 19:35:36 +00:00
def call(context)
begin
call_next(context)
2016-11-16 17:27:01 +00:00
rescue ex : Kemal::Exceptions::RouteNotFound
call_exception_with_status_code(context, ex, 404)
rescue ex : Kemal::Exceptions::CustomException
call_exception_with_status_code(context, ex, context.response.status_code)
2016-05-05 20:12:17 +00:00
rescue ex : Exception
2016-12-03 22:27:26 +00:00
log("Exception: #{ex.inspect_with_backtrace}\n")
2016-11-16 17:27:01 +00:00
return call_exception_with_status_code(context, ex, 500) if Kemal.config.error_handlers.has_key?(500)
2016-05-05 19:35:36 +00:00
verbosity = Kemal.config.env == "production" ? false : true
2016-05-05 20:12:17 +00:00
return render_500(context, ex.inspect_with_backtrace, verbosity)
2016-05-05 19:35:36 +00:00
end
2016-02-14 10:43:25 +00:00
end
2016-11-16 17:27:01 +00:00
def call_exception_with_status_code(context, exception, status_code)
if Kemal.config.error_handlers.has_key?(status_code)
context.response.content_type = "text/html" unless context.response.headers.has_key?("Content-Type")
2016-11-16 17:27:01 +00:00
context.response.print Kemal.config.error_handlers[status_code].call(context, exception)
context.response.status_code = status_code
context
end
end
2016-02-14 10:43:25 +00:00
end
end