kemal/src/kemal/exception_handler.cr

31 lines
1.3 KiB
Crystal
Raw Normal View History

2016-05-05 19:35:36 +00:00
module Kemal
2017-10-06 11:53:53 +00:00
# Handles all the exceptions, including 404, custom errors and 500.
class ExceptionHandler
2016-12-24 11:22:44 +00:00
include HTTP::Handler
2016-05-05 19:35:36 +00:00
INSTANCE = new
2016-02-14 10:43:25 +00:00
2017-08-25 13:41:02 +00:00
def call(context : HTTP::Server::Context)
call_next(context)
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)
rescue ex : Exception
log("Exception: #{ex.inspect_with_backtrace}")
return call_exception_with_status_code(context, ex, 500) if Kemal.config.error_handlers.has_key?(500)
verbosity = Kemal.config.env == "production" ? false : true
2019-06-13 11:31:45 +00:00
render_500(context, ex, verbosity)
2016-02-14 10:43:25 +00:00
end
2017-08-24 20:32:43 +00:00
private def call_exception_with_status_code(context : HTTP::Server::Context, exception : Exception, status_code : Int32)
return if context.response.closed?
2017-10-06 10:41:22 +00:00
if !Kemal.config.error_handlers.empty? && Kemal.config.error_handlers.has_key?(status_code)
context.response.content_type = "text/html" unless context.response.headers.has_key?("Content-Type")
context.response.status_code = status_code
2018-12-25 16:06:07 +00:00
context.response.print Kemal.config.error_handlers[status_code].call(context, exception)
context
end
end
2016-02-14 10:43:25 +00:00
end
end