Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Làm Chủ Exception Handling Trong Ruby: Hướng Dẫn Thực Tế

Tại AppSignal chúng tôi cung cấp error tracking cho Ruby applications. Để làm vậy, chúng tôi capture all exceptions applications throw at us và notify developers as they happen.

Có thể difficult get exception handling right. Trong bài này chúng ta explain cách nó works, problems bad handling can cause và how to rescue exceptions properly.

Rescuing Exceptions (Bắt Ngoại Lệ)

Bằng cách rescuing exceptions trong Ruby bạn prevent application từ crashing ngay khi something goes wrong. Với begin .. rescue block bạn specify alternative path cho application khi error occurs.

begin
  file = File.open("config.yml")
  config = YAML.load(file)
rescue
  puts "Could not load config, using defaults"
  config = default_config
end

Cũng possible specify exceptions nào should be rescued. Khi specify exception class, all subclasses của exception này cũng sẽ captured.

begin
  File.open("config.yml")
rescue SystemCallError => e
  puts "System error: #{e.message}"
end

Trong ví dụ trên bạn thấy exception Errno::ENOENT bị caught khi parent SystemCallError được rescued.

Rescuing Too High Up In Exception Chain (Bắt Quá Cao Trong Chuỗi Ngoại Lệ)

Quan trọng không rescue exceptions too high up the Exception chain. Khi bạn làm vậy, all subclassed exceptions cũng bị caught, making rescue block's capture too generic.

Chương trình sau read config file based on argument passed to program.

def read_config(file)
  File.read(file)
rescue
  puts "Could not read config file"
end

read_config("config.yml")
# Output: "Could not read config file"

Error message nói couldn't read config file, nhưng real problem là typo trong code.

def read_config(file)
  File.read(file)
rescue
  puts "Could not read config file"
end

read_config("config.yml")
# Thực tế: NoMethodError: undefined method `read' for "config.yml":String
# Nhưng bị catch bởi rescue generic

Default exception class caught by begin .. rescue block là StandardError. Nếu không pass specific class, Ruby rescue StandardError và all subclassed errors. NoMethodError là một trong những errors này.

Rescue specific exception class giúp prevent unrelated errors accidentally prompt failure state. Nó cũng allow more specific custom error messages helpful cho end user.

def read_config(file)
  File.read(file)
rescue Errno::ENOENT => e
  puts "Config file not found: #{e.message}"
rescue Errno::EACCES => e
  puts "Permission denied: #{e.message}"
end

Rescuing Exception (Bắt Exception Class Gốc)

Vẫn tempting rescue high up in exception chain. Rescue all errors app can raise sẽ prevent crash. (100% uptime here we come!) Tuy nhiên, nó cause lots of problems.

Exception class là main exception class trong Ruby. All other exceptions là subclasses; nếu Exception rescued, all errors caught.

Hai exceptions most applications won't want to rescue là SignalException và SystemExit.

SignalException dùng khi outside source tell application stop. Có thể OS khi muốn shutdown, hoặc system admin muốn stop application.

SystemExit dùng khi exit called từ Ruby application. Khi raised, developer muốn application stop.

Nếu rescue Exception và exceptions này raised while application đang chạy begin ... rescue ... end block, nó cannot exit.

Generally bad idea rescue Exception trong normal situations. Khi rescue Exception, bạn prevent SignalException và SystemExit function, nhưng cũng LoadError, SyntaxError, NoMemoryError, to name a few. Better rescue more specific exceptions instead.

Failures In Tests (Thất Bại Trong Tests)

Khi Exception rescued, dùng rescue Exception => e, other things beside application could break. Test suite actually could hide some errors.

Trong minitest và RSpec, assertions fail sẽ raise exception để inform về failed assertion, failing test. Khi làm vậy, họ raise own custom exceptions, subclassed from Exception.

Nếu Exception rescued in test hoặc application code, nó could be silencing assertion failure.

# Test code
test "user is valid" do
  user = User.new(name: "")
  assert user.valid?
rescue Exception => e
  # Silences the assertion failure!
  puts "Error: #{e.message}"
end

Expecting Exceptions (Mong Đợi Ngoại Lệ)

Some code meant to raise exceptions. Trong test suite possible simply silence exception để test not fail khi raised.

# Bad: chỉ silence exception
begin
  raise "Something went wrong"
rescue
  # test passes even if exception not raised!
end

Tuy nhiên, điều này không test nếu exception was raised hoặc not. Khi exception not raised, test won't tell nếu behavior still correct.

Possible assert nếu exception raised, và nếu không, exception nào was.

# Good: assert exception raised
assert_raises(RuntimeError) do
  raise "Something went wrong"
end

# Hoặc với Minitest
assert_raises(ActiveRecord::RecordNotFound) do
  User.find(999999)
end

Re-raise Exception (Raise Lại Ngoại Lệ)

Application should only capture exceptions as high up as Exception class khi có very good reason. Ví dụ, khi có cleanup involved trước exiting block, như remove temporary files really need removed.

One recommendation khi absolutely have to rescue Exception, re-raise it after done handling error. Cách này Ruby exception handling decide fate of process afterward.

begin
  # critical operation
  File.write("/tmp/lockfile", Process.pid)
  # do work
rescue Exception => e
  # cleanup
  File.delete("/tmp/lockfile") if File.exist?("/tmp/lockfile")
  # re-raise để Ruby decide
  raise e
end

Unsure What To Rescue? (Không Chắc Rescue Gì?)

Như mentioned earlier, good to be specific in what errors to rescue.

Khi unsure what exceptions operation can raise, rescue StandardError có thể good place to start. Run code trong different scenarios và see what exceptions it raises.

begin
  # risky operation
rescue StandardError => e
  # log error
  logger.error(e)
  # re-raise or handle
  raise
end

Mỗi khi encounter new exception, add specific rescue cases cho those exceptions hoặc relevant parent class. Better be specific in what to rescue than rescue too many exceptions.

begin
  # operation
rescue ActiveRecord::RecordNotFound => e
  # handle not found
rescue ActiveRecord::RecordInvalid => e
  # handle validation error
rescue StandardError => e
  # handle other standard errors
  raise
end

Đây kết thúc primer về exception handling trong Ruby. Let us know at @AppSignal nếu muốn know more, hoặc có specific question. Nếu muốn better insight vào where và how often exceptions raised in app, give AppSignal a try.

Làm Chủ Exception Handling Trong Ruby: Hướng Dẫn Thực Tế

Tom de Bruijn