更短的 Rails 异常错误消息

问题描述 投票:0回答:1

我正在挽救类似的错误

undefined local variable or method 'something' for #<PdfHelper::MyPdfHelper...................@stream="\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00........................"

这里的@stream基本上存储了整个原始pdf数据,因此错误消息非常非常长。我需要将此错误消息保存到记录中,但以更短的方式,有什么好的方法可以做到这一点,而不是仅仅将消息截断为几个字符?

我尝试将其截断为仅几百个字符,但正在寻找更好的方法。

ruby-on-rails ruby pdf-generation
1个回答
0
投票

为了更有效地处理错误消息,您可以专注于提取消息中最相关的部分,而不仅仅是截断它。这是实现它的分步方法:

  1. 提取错误消息,不包括@stream中的原始PDF数据。
  2. 使用正则表达式通过删除或替换来清理错误消息 不需要的部分。
  3. 将错误消息保存在详细日志文件或专用错误中 如果需要的话,记录表以供进一步检查。
  4. 创建包含基本信息的错误消息的简明摘要。

这是此方法的一个示例:

begin
  # Code that might raise an error
rescue => e
  error_message = e.message

  # Use regex to remove the raw PDF data part (assuming @stream is what you want to remove)
  # The regex @stream="[^"]*" targets the @stream part of the error message and replaces it with [REDACTED]
  cleaned_message = error_message.gsub(/@stream="[^"]*"/, '@stream="[REDACTED]"')

  # Optionally, further reduce the size by truncating if needed
  summary_message = cleaned_message.truncate(300) # Adjust the length as needed

  # Save the cleaned and shortened error message to a record
  ErrorLog.create(message: summary_message)

  # Also log the complete error message for debugging purposes
  Rails.logger.error(e.full_message)

  # Or save the complete error message to a detailed error log
  DetailedErrorLog.create(message: e.full_message)
end
© www.soinside.com 2019 - 2024. All rights reserved.