我有一个vanilla Rails应用程序,它只包含一个带有标题和内容属性的简单Post
模型。
我从the official Rails guide获取了ActiveJob
例外情况,其示例如下:
class ExceptionTestJob < ApplicationJob
queue_as :default
rescue_from(ActiveRecord::RecordNotFound) do |exception|
logger.error("Could not find given post")
end
def perform(post_id)
post = Post.find(post_id)
end
end
如果我尝试使用不存在的帖子ID运行作业,我会得到完整的堆栈跟踪和错误消息“找不到给定的帖子”。
我不想获得堆栈跟踪。我只想获得rescue_from
块中执行的代码。如何抑制堆栈跟踪?
修改:
如果我在方法中使用常规rescue
,请执行以下操作:
class ExceptionTestJob < ApplicationJob
def perform(post_id)
begin
Post.find(post_id)
rescue ActiveRecord::RecordNotFound
logger.error("Could not find given post")
end
end
end
异常将在没有回溯的情况下被捕获(如预期的那样),但作业将成功完成:Performed ExceptionTestJob (Job ID: c21ce397-b19b-4464-9e53-696707b87dde) from Async(default) in 13.84ms
。
答案 0 :(得分:-1)
我认为它会对你有所帮助
begin
raise
rescue => e
logger.error e.message
logger.error e.backtrace.join("\n")
end