0

I have the following routing rules that would catch the HTTP status for some 'errors' and redirect the user to the error page:

%w[403 404 422 500 503].each do |code|
  match code, to: 'errors#show', code: code, via: :all
end

I also have the root namespace and another one for 'admin'. I'd like to make this same route matching work for the admin namespace, so I added the same routing rules to it:

namespace :admin do
    %w[403 404 422 500 503].each do |code|
          match code, to: 'errors#show', code: code, via: :all
    end
end

PROBLEM : It doesn't work and all the 403 requests are being redirected to /403 instead of /admin/403. Is there a way to achieve this goal?

I want to do it like this because I need to use different layouts for the error pages to show them with the application layout and also with the admin layout.

max
  • 96,212
  • 14
  • 104
  • 165
RafaelTSCS
  • 1,234
  • 2
  • 15
  • 36
  • 2
    You need to tell rails to use your routes as the exception app - add `config.exceptions_app = self.routes` to `config/application.rb`. https://mattbrictson.com/dynamic-rails-error-pages – max Sep 08 '17 at 16:04
  • I didn't explain myself very good. I already did this. The routing is working, but only for the root namespace. It doesn't work for the namespace admin. – RafaelTSCS Sep 08 '17 at 16:25
  • I don't really think this is possible. Rails will only call one exceptions app and does not really map to your idea of namespaces. When rails handles the exception it does not care if it originated in your namespace. – max Sep 08 '17 at 16:36
  • You could solve it by using a different rails app for the admin interface. But it might be simler to just solve it with good UI design. – max Sep 08 '17 at 16:45

1 Answers1

0

You should probably use a diff namespaced errors controller. You can do something like rails generate scaffold_controller admin::errors. Then setup your routes so use the new namespaced controller:

Rails.application.routes.draw do
  root 'home#index'
  %w[403 404 422 500 503].each do |err|
    match err, to: 'errors#show', code: err, via: :all
  end
  namespace :admin do
    %w[403 404 422 500 503].each do |err|
      match err, to: 'admin/errors#show', code: err, via: :all
    end
  end
end

Edit: Look into "concerns" for moving dup code between both error controllers to more of a DRY setup

Derek Wright
  • 1,452
  • 9
  • 11
  • I don't believe this works the way you were intending it to, as the comment on the above question mentions - rails does not distinguish between namespaces at this point. (When the exceptions are being handled by the routes as the exceptions app). It appears that the exceptions are sent to only the non-namespaced route. – ARun32 Jun 17 '20 at 20:24