简体   繁体   中英

Do DB constraints cause Ruby to crash and should I rescue them or not?

I'm reading an article which says all Exceptions cause Ruby to crash. http://blog.honeybadger.io/a-beginner-s-guide-to-exceptions-in-ruby/

I've got some DB schema constraints:

create_table :options_sets do |t|
    t.boolean :shared, :null => false
end

So when I create a new options_set that violates the constraint, causing the exception, I don't know how to check whether the server has restarted, but it doesn't look like it to me.

OptionsSet.create()

Error Msg:

ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR:  null value in column "shared" violates not-null constraint

I've also read many times that "exceptions should not be expected" and that you shouldn't rely exclusively on model validation for various reasons (like race conditions). So it seems to me that this is an exception that must be expected sometimes.

So, should I be rescuing this exception or should it be handled in another way?

Rails handles all otherwise unhandled exceptions and turns them into HTML error pages. Ruby does not "crash" or restart just because you failed to rescue an exception in your Rails application.

So, should I be rescuing this exception or should it be handled in another way?

You should be using validations in your model to prevent you from reaching database-level exceptions.

The exception that you see here is one that is caused by a faulty programming statement. If you have a bare

OptionsSet.create()

in your code, this statement is the error and it should be fixed. No need to rescue / handle anything. If, however this exception could be caused by user input or other program state, eg

OptionsSet.create(shared: some_expression_which_may_evaluate_to_nil)

then you should handle the exception to allow your application to return a meaningful error message to the user, allowing him/her to correct the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM