Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a 404 Not Found default error page "Active Record::RecordNotFound" when I have a custom page for that

I have a custom error pages for 404 & 500 status code, and it's works fine when I put localhost:3000/something.html. But don't works when I put localhost:3000/controller/element_of_a_model.

routes.rb:

if Rails.env.production? then
  unless Rails.application.config.consider_all_requests_local
    get '*not_found', to: 'errors#error_404'
    get '*internal_server_error', to: 'errors#error_500'
  end
else
  unless
    get '*not_found', to: 'errors#error_404'
    get '*internal_server_error', to: 'errors#error_500'
  end
end

ErrorsController:

def error_404
    render_error 404
end

def error_500
    render_error 500
end

private
   def render_error(status)
       respond_to do |format|
           format.html { render 'error_' + status.to_s() + '.html', :status => status, :layout => 'errors'}
           format.all { render :nothing => true, :status => status }
   end
end
like image 210
luisantruiz Avatar asked Mar 22 '23 11:03

luisantruiz


1 Answers

You have to put this in application controller:

rescue_from ActiveRecord::RecordNotFound do |exception|
  render_error 404
end


def render_error(status)
  respond_to do |format|
    format.html { render 'error_' + status.to_s() + '.html', :status => status, :layout => 'errors'}
    format.all { render :nothing => true, :status => status }
  end
end

Actually your ErrorController will be triggered by routes, but you have to add logic for exceptions.

like image 198
apneadiving Avatar answered Mar 24 '23 00:03

apneadiving