class Errors < Protocol::HTTP::Middleware
- Inherits from
Protocol::HTTP::Middleware
A middleware which performs internal redirects based on error status codes.
Place this middleware after client-visible redirection middleware in the application configuration. Internal error-document requests invoke the delegate directly, bypassing middleware configured before this one.
Definitions
def initialize(app, codes = {})
Implementation
def initialize(app, codes = {})
super(app)
@codes = codes
end
def freeze
Freeze this object and its internal state.
Signature
-
returns
self This object.
Implementation
def freeze
return self if frozen?
@codes.freeze
super
end
def unhandled_error?(response)
Check whether the response status requires error handling.
Signature
-
parameter
responseProtocol::HTTP::Response The response.
-
returns
Boolean Whether the response is an error without handler-provided headers.
Implementation
def unhandled_error?(response)
response.status >= 400 && response.headers.empty?
end
def call(request)
Replace an unhandled error response with its configured error document.
Signature
-
parameter
requestUtopia::Request The request.
-
returns
Protocol::HTTP::Response The original or error-document response.
-
raises
RequestFailure If the configured error document also fails.
Implementation
def call(request)
response = Response.wrap(@delegate.call(request))
if unhandled_error?(response) && location = @codes[response.status]
resource_status = response.status
# The original response is replaced by the configured error document:
response.close
error_request = request.with(method: "GET", path: location)
error_response = Response.wrap(@delegate.call(error_request))
if error_response.status >= 400
error = RequestFailure.new(request.url.path.encoded, resource_status, location, error_response.status)
# The failed error document will not be returned to the server:
error_response.close(error)
raise error
else
# Feed the error code back with the error document:
error_response.status = resource_status
return error_response
end
else
return response
end
end