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.
|
2017-10-06 17:34:18 +00:00
|
|
|
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)
|
2016-05-05 19:35:36 +00:00
|
|
|
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
|
2017-03-12 12:37:23 +00:00
|
|
|
log("Exception: #{ex.inspect_with_backtrace}")
|
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-07-03 09:13:11 +00:00
|
|
|
|
2017-08-24 20:32:43 +00:00
|
|
|
private def call_exception_with_status_code(context : HTTP::Server::Context, exception : Exception, status_code : Int32)
|
2017-10-06 10:41:22 +00:00
|
|
|
if !Kemal.config.error_handlers.empty? && Kemal.config.error_handlers.has_key?(status_code)
|
2016-11-06 08:58:18 +00:00
|
|
|
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)
|
2016-11-23 17:36:56 +00:00
|
|
|
context.response.status_code = status_code
|
2016-11-06 08:58:18 +00:00
|
|
|
context
|
2016-07-03 09:13:11 +00:00
|
|
|
end
|
|
|
|
end
|
2016-02-14 10:43:25 +00:00
|
|
|
end
|
|
|
|
end
|