【发布时间】:2024-05-01 15:35:02
【问题描述】:
在这篇文章中,错误在 api 和基本控制器方法中都得到了解决。但它可能不是处理错误的最佳方法,原因如下:
- 脂肪控制器
- 干燥
- 可维护性
在 ActionController::Base 中,我们只在 ApplicationController 中处理了 ActiveRecord::RecordNotFound。但是对于 ActionController::API 我必须在每个控制器中拯救 ActiveRecord::RecordNotFound 。那么有没有最好的方法来处理这个问题呢?
为 API 使用 Rails 5 和“active_model_serializers”gem
ActionController::API
module Api
module V1
class UsersController < ActionController::API
before_action :find_user, only: :show
def find_user
@user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
render json: { error: e.to_s }, status: :not_found
end
end
end
end
ActionController::Base
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
render file: "#{Rails.root}/public/404", layout: true, status: :not_found
end
end
【问题讨论】:
-
@icemelt 这对我来说很有意义 :) 还有其他解决方案吗?
标签: ruby-on-rails activerecord active-model-serializers