|
2 | 2 | require "action_controller/metal" |
3 | 3 |
|
4 | 4 | module RestfulError |
5 | | - class ExceptionsController < ::ActionController::Metal |
6 | | - include AbstractController::Rendering |
7 | | - include ActionView::Layouts |
8 | | - include ActionController::Rendering |
9 | | - |
10 | | - def self.controller_path = "restful_error" |
11 | | - append_view_path File.join(File.dirname(__FILE__), "../../app/views") |
12 | | - layout nil |
| 5 | + class ExceptionsApp |
| 6 | + Config = Struct.new(:enable, :inherit_from, :fallback) |
| 7 | + def self.config |
| 8 | + Config.new.tap do |config| |
| 9 | + config.enable = true |
| 10 | + config.inherit_from = "::ApplicationController" |
| 11 | + end |
| 12 | + end |
13 | 13 |
|
14 | | - def show |
15 | | - @exception = request.env["action_dispatch.exception"] |
16 | | - code = request.path_info[1..].to_i |
17 | | - status = RestfulError.build_status_from_symbol_or_code(code) |
18 | | - @status_code = status.code |
19 | | - @reason_phrase = status.reason_phrase |
20 | | - @response_message = @exception.try(:response_message) || RestfulError.localized_phrase(@exception.class.name, status) || nil |
| 14 | + def initialize(config = self.class.config) |
| 15 | + @config = config |
| 16 | + end |
| 17 | + def call(env) |
| 18 | + return @config.fallback.call(env) unless @config.enable |
| 19 | + app.call(env) |
| 20 | + rescue Exception => _e |
| 21 | + raise unless @config.fallback |
| 22 | + @config.fallback.call(env) |
| 23 | + end |
21 | 24 |
|
22 | | - render status: status.code, formats: request.format.symbol |
| 25 | + def app |
| 26 | + @app ||= begin |
| 27 | + # To use "layouts/application" we need inherit from ::ApplicationController |
| 28 | + # It is not defined at config time, so we need to load it here |
| 29 | + if @config.inherit_from && Object.const_defined?(@config.inherit_from) |
| 30 | + inherit_from = @config.inherit_from.constantize |
| 31 | + else |
| 32 | + inherit_from = RestfulError::ApplicationController |
| 33 | + end |
| 34 | + RestfulError.const_set("SuperController", inherit_from) |
| 35 | + ExceptionsController.action(:show) |
| 36 | + end |
23 | 37 | end |
24 | 38 | end |
25 | | - |
26 | | - ExceptionsApp = ExceptionsController.action(:show) |
27 | 39 | end |
0 commit comments