iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 28
0
影片教學

懶人寫寫 BOT系列 第 28

Day 28 Error Handling - Clean Code Ruby

嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby

Error Handling

掌握錯誤

可能出錯的地方 log 且導向相關 user 或統計工具

Bad:

require 'logger'

logger = Logger.new(STDOUT)

begin
  function_that_might_throw()
rescue StandardError => err
  logger.info(err)
end

Good:

require 'logger'

logger = Logger.new(STDOUT)
# Change the logger level to ERROR to output only logs with ERROR level and above
logger.level = Logger::ERROR

begin
  function_that_might_throw()
rescue StandardError => err
  # Option 1: Only log errors
  logger.error(err)
  # Option 2: Notify end-user via an interface
  notify_user_of_error(err)
  # Option 3: Report error to a third-party service like Honeybadger
  report_error_to_service(err)
  # OR do all three!
end

說明錯誤

Bad:

def initialize(user)
  fail unless user
  ...
end

Good:

def initialize(user)
  fail ArgumentError, 'Missing user' unless user
  ...
end

上一篇
Day 27 Testing - Clean Code Ruby
下一篇
Day 29 Formatting - Clean Code Ruby
系列文
懶人寫寫 BOT30

尚未有邦友留言

立即登入留言