【发布时间】:2022-10-25 03:17:52
【问题描述】:
在我的 Rails 7 应用程序中,我使用了几个 3rd 方 API 来提供获取数据。每次我收到错误时,我都必须 rescue 和 nil 仍然能够将用户重定向到所需的页面,例如:
# lib/custom_api.rb
module CustomApi
extend self
def fetch_transactions(user_id)
client.transactions.list(user_id:)
# rescue from custom error
rescue Errors::NotFoundError
nil
end
end
# transactions_controller.rb
class TransactionsController < ApplicationController
def index
transaction_list = CustomApi.fetch_transactions(current_user.id)
if transaction_list
@transactions = transaction_list
else
@transactions = transaction_list
flash[:alert] = 'No transactions'
end
end
end
# views/transactions/index.html.erb
<%= turbo_frame_tag 'transactions' do %>
<%= render partial: 'table_headers' %>
<%= render Transactions::TableComponent.new(records: @transactions) if @transactions %>
<% end %>
一切正常,但我有 50 个端点需要包含 rescue Errors::NotFoundError,而且我认为重复这条线 50 次是不够的。有没有办法避免这种情况?
【问题讨论】:
-
你写了:重复这条线50次就足够了.你的意思是什么线?你到底在优化什么?
-
@spickermann 我的意思是
rescue Errors::NotFoundError nil -
在对我的回答的评论中,您写道您有时会处理
Errors::NotFoundError而不是返回nil。当您使用nil进行救援以及您做一些不同的事情时,是否有一种模式? -
@spickermann 我有 114 个用于该 API 的端点。处理
NotFoundError至少有 4 种可能的情况 - 1. 返回nil并在控制器内显示一条闪烁消息(我的情况); 2. 显示一则消息和redirect_to request.referrer; 3.redirect_to home; 4. 呼叫外部工人。当然,大小写取决于被调用的端点。
标签: ruby-on-rails ruby