ruby ruby自定义异常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby ruby自定义异常相关的知识,希望对你有一定的参考价值。

# 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

以上是关于ruby ruby自定义异常的主要内容,如果未能解决你的问题,请参考以下文章

ruby MiniTest:断言自定义异常(ERROR)

使用 Ruby 发送自定义 HTTP 标头

用于自定义标记语言的 Ruby 标记解析器

Ruby:自定义 gem 需要其中的模块“要求”

ruby Rails中自定义rake任务

ruby ActiveAdmin自定义模板