kitaro-tn
4/13/2016 - 2:37 PM

ruby custom exception

ruby custom exception

# coding: utf-8

require 'logger'
require 'json'

ENV["TZ"] = "Asia/Tokyo"

##
# 自作logger class
class MyLogger < Logger

  def debug(progname = nil, method_name = nil, msg)
    super(progname) { { method_name: method_name, message: msg } }
  end

  def info(progname = nil, method_name = nil, msg)
    super(progname) { { method_name: method_name, message: msg } }
  end

  def warn(progname = nil, method_name = nil, msg)
    super(progname) { { method_name: method_name, message: msg } }
  end

  def error(progname = nil, method_name = nil, msg, error_code, backtrace)
    super(progname) { { method_name: method_name, message: msg, error_code: error_code, backtrace: backtrace } }
  end

  def fatal(progname = nil, method_name = nil, msg, error_code, backtrace)
    super(progname) { { method_name: method_name, message: msg, error_code: error_code, backtrace: backtrace } }
  end

  ##
  # logをjson形式で
  class JSONFormatter < Logger::Formatter

    def call(severity, time, progname, msg)
      { level: severity, time: time, program_name: progname.to_s, content: msg }.to_json + "\n"
    end
  end

end

##
# 自作exception class
class MyException < StandardError

  def initialize(error_code, message)
    @code = error_code
    super("[#{error_code}] - #{message}")
  end

  def self.exception(error_code, message)
    self.new(error_code, message)
  end

  def self.throw(error_code)
    self.new(error_code, error_message(error_code))
  end

  def self.error_message(error_code)
    # error_codeをyaml等で管理しておくと便利
  end

end

##
# 例外補足にエラーコードを取れるように
Exception.class_eval do

  def code
    @code ||= "---"
  end

end


class ExceptionTest

  def error
    begin
      raise MyException.exception("100", "Error1")
    rescue => e
      raise e
    end
  end

  def default_error

    begin
      raise StandardError.new "StandardError"
    rescue => e
      raise e
    end
  end

end

test = ExceptionTest.new
logger = MyLogger.new(STDOUT)

begin
  test.error
rescue MyException => e
  logger.error(self, e.message, e.code, e.backtrace)
rescue => e
  logger.error(self, e.message, e.code, e.backtrace)
end

logger.formatter = MyLogger::JSONFormatter.new
begin
  test.default_error
rescue => e
  logger.error(self, e.message, e.code, e.backtrace)
end