2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-01-12 11:15:10 +08:00
|
|
|
# since all the rescue from clauses are not caught by the application controller for matches
|
|
|
|
# we need to handle certain exceptions here
|
|
|
|
module Middleware
|
|
|
|
class DiscoursePublicExceptions < ::ActionDispatch::PublicExceptions
|
|
|
|
|
|
|
|
def initialize(path)
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
# this is so so gnarly
|
|
|
|
# sometimes we leak out exceptions prior to creating a controller instance
|
|
|
|
# this can happen if we have an exception in a route constraint in some cases
|
|
|
|
# this code re-dispatches the exception to our application controller so we can
|
|
|
|
# properly translate the exception to a page
|
|
|
|
exception = env["action_dispatch.exception"]
|
|
|
|
response = ActionDispatch::Response.new
|
|
|
|
|
2018-10-05 12:33:08 +08:00
|
|
|
# Special handling for invalid params, in this case we can not re-dispatch
|
|
|
|
# the Request object has a "broken" .params which can not be accessed
|
|
|
|
exception = nil if Rack::QueryParser::InvalidParameterError === exception
|
|
|
|
|
2018-12-13 15:27:02 +08:00
|
|
|
# We also can not dispatch bad requests as no proper params
|
|
|
|
exception = nil if ActionController::BadRequest === exception
|
|
|
|
|
2018-01-12 11:15:10 +08:00
|
|
|
if exception
|
2018-01-23 06:00:08 +08:00
|
|
|
begin
|
|
|
|
fake_controller = ApplicationController.new
|
|
|
|
fake_controller.response = response
|
2019-11-21 12:51:18 +08:00
|
|
|
fake_controller.request = request = ActionDispatch::Request.new(env)
|
|
|
|
|
2020-01-02 09:34:38 +08:00
|
|
|
# We can not re-dispatch bad mime types
|
2019-11-21 12:51:18 +08:00
|
|
|
begin
|
|
|
|
request.format
|
|
|
|
rescue Mime::Type::InvalidMimeType
|
2021-11-13 02:52:25 +08:00
|
|
|
return [400, { "Cache-Control" => "private, max-age=0, must-revalidate" }, ["Invalid MIME type"]]
|
2019-11-21 12:51:18 +08:00
|
|
|
end
|
2018-01-12 11:15:10 +08:00
|
|
|
|
2018-01-23 06:00:08 +08:00
|
|
|
if ApplicationController.rescue_with_handler(exception, object: fake_controller)
|
|
|
|
body = response.body
|
|
|
|
if String === body
|
|
|
|
body = [body]
|
|
|
|
end
|
|
|
|
return [response.status, response.headers, body]
|
|
|
|
end
|
|
|
|
rescue => e
|
|
|
|
Discourse.warn_exception(e, message: "Failed to handle exception in exception app middleware")
|
2018-01-12 11:15:10 +08:00
|
|
|
end
|
2018-01-23 06:00:08 +08:00
|
|
|
|
2018-01-12 11:15:10 +08:00
|
|
|
end
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|