Exceptions in

RoR

Examples rescue


raise                                          # Приклад 1
raise "Виникла помилка"                          # Приклад 2
raise ArgumentError                            # Приклад 3
raise ArgumentError,    "Невірні дані"            # Приклад 4
raise ArgumentError.new("Невірні дані")           # Приклад 5
raise ArgumentError,    "Невірні дані", caller[0] # Приклад 6

raise - не зарезервоване слово,

а метод модуля Kernel (fail)

2 - RuntimeError

 

6 - "filename:line:in 'method'" в масиві caller

Examples begin-end

begin
 x = Math.sqrt(y/z)
 # ...
rescue ArgumentError
 puts "Виникла помилка про вичислені кореня."
rescue ZeroDivisionError
 puts "Спроба ділення на нуль."
end

begin
 x = Math.sqrt(y/z)
 # ...
rescue => err
 puts err
end

err - Перехоплює всі виключення від класу StandartError

Examples rescue in method

begin
 # Код, в якому може виникнути помилка...
rescue Type1
 # ...
rescue Type2
 # ...
else
 # Інші виключення...
end

begin
 # Код, в якому може виникнути помилка...
rescue
 # Пробує відновити...
 retry # Пробує ще раз.
end
begin
 # Код, в якому може виникнути помилка...
rescue
 # Пробує відновити...
ensure
 # Цей код виконається в будь-якому випадку.
end

x = a/b rescue puts("Ділення на нуль!")

def some_method
 # Код...
rescue
 # Відновлення після помилки...
end

Text

Exception
 NoMemoryError
 ScriptError
   LoadError
   NotImplementedError
   SyntaxError
 SignalException
   Interrupt
 StandardError
   ArgumentError
   IOError
     EOFError
   IndexError
   LocalJumpError
   NameError
     NoMethodError
   RangeError
     FloatDomainError
   RegexpError
   RuntimeError
   SecurityError
   SystemCallError
   SystemStackError
   ThreadError
   TypeError
   ZeroDivisionError
 SystemExit
 fatal

Examples

class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :deny_access # self defined exception
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  rescue_from 'MyAppError::Base' do |exception|
    render xml: exception, status: 500
  end

  protected
    def deny_access
      ...
    end

    def show_errors(exception)
      exception.record.new_record? ? ...
    end
end

Examples

# Add this in your config/routes.rb
match '*path', :to => 'application#routing_error'


# Add this to your application_controller.rb
def routing_error(error = 'Routing error', status = :not_found, exception=nil)
render_exception(404, "Routing Error", exception)
end
# config/environments/production.rb

...
config.consider_all_requests_local = false
...
config.exceptions_app = -> (env) { ExceptionsController.action(:error).call(env) }
...

# views/exceptions/error.html.haml

...
= @status
= @name
= @message
...

Examples

Exceptions

By dima_chornenky

Exceptions

  • 353