Rails - How to handle database connectivity and gracefully inform the user that database is unreachable

254 Views Asked by At

I am working on a rails 5 API that has SQLite3 database. Even though the database file is stored locally, I want to create my own exception handling in case the database file is not accessible, e.g. deleted. I actually want all such errors, that are caused by DB connectivity to create my own custom response and display it to the user, in text,json etc.

How can I achieve this? At the moment when I delete the database I get the error message about "Pending migration" or If I change the database filename to something else I get the error "Can't open database file". For all similar scenarios related to database I want to handle the error my own way.

Any ideas?

Thanks

1

There are 1 best solutions below

0
B Seven On

rescue_from

https://apidock.com/rails/ActiveSupport/Rescuable/ClassMethods/rescue_from

You'll need to find the name of the exception(s) thrown.

Here's an example:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  private
    def show_errors(exception)
      render ...
    end
end