Class: Middleware::DiscoursePublicExceptions

Inherits:
ActionDispatch::PublicExceptions
  • Object
show all
Defined in:
lib/middleware/discourse_public_exceptions.rb

Constant Summary collapse

INVALID_REQUEST_ERRORS =
Set.new(
  [
    Rack::QueryParser::InvalidParameterError,
    ActionController::BadRequest,
    ActionDispatch::Http::Parameters::ParseError,
    ActionController::RoutingError,
  ],
)

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ DiscoursePublicExceptions

Returns a new instance of DiscoursePublicExceptions.



17
18
19
# File 'lib/middleware/discourse_public_exceptions.rb', line 17

def initialize(path)
  super
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/middleware/discourse_public_exceptions.rb', line 21

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

  exception = nil if INVALID_REQUEST_ERRORS.include?(exception)

  if exception
    begin
      fake_controller = ApplicationController.new
      fake_controller.response = response
      fake_controller.request = request = ActionDispatch::Request.new(env)

      # We can not re-dispatch bad mime types
      begin
        request.format
      rescue Mime::Type::InvalidMimeType
        return [
          400,
          { "Cache-Control" => "private, max-age=0, must-revalidate" },
          ["Invalid MIME type"]
        ]
      end

      # Or badly formatted multipart requests
      begin
        request.POST
      rescue ActionController::BadRequest => error
        if error.cause.is_a?(EOFError)
          return [
            400,
            { "Cache-Control" => "private, max-age=0, must-revalidate" },
            ["Invalid request"]
          ]
        else
          raise
        end
      end

      if ApplicationController.rescue_with_handler(exception, object: fake_controller)
        body = response.body
        body = [body] if String === body
        return response.status, response.headers, body
      end
    rescue => e
      return super if INVALID_REQUEST_ERRORS.include?(e.class)
      Discourse.warn_exception(
        e,
        message: "Failed to handle exception in exception app middleware",
      )
    end
  end
  super
end