rails 5 api应用程序具有json错误响应,而不是html错误响应



如果我使用--api标志在rails中创建应用程序,我的错误响应是html而不是json。

如何更改默认的错误处理程序,以便每当在控制器操作中引发错误时,我都会收到一个只包含json的响应,其中包含错误和http状态?

现在我在每个自定义操作中都使用下面的代码

rescue => e
response.status = 422
render json: { error: e.message }

我不想每次都加这个。。。

更新:我在应用程序控制器中使用了rescue_from方法

rescue_from Exception do |exception|
render json: exception, status: 500
end

但我觉得这是非常错误的,状态总是硬编码为500

您可以在路由中添加json格式,这样它将始终接受json格式的请求,如下面的

namespace :api, as: nil, defaults: { format: :json } do
devise_for :users, controllers: {
registrations: "api/v1/users/registrations",
passwords: "api/v1/users/passwords"
}
resources :products, only: [:show,:index] do
get "check_product_avaibility"
get "filter", on: :collection
end
end

为了全局处理错误,您可以在应用程序控制器文件中添加around_action

around_action :handle_exceptions, if: proc { request.path.include?('/api') }
# Catch exception and return JSON-formatted error
def handle_exceptions
begin
yield
rescue ActiveRecord::RecordNotFound => e
@status = 404
@message = 'Record not found'
rescue ActiveRecord::RecordInvalid => e
render_unprocessable_entity_response(e.record) && return
rescue ArgumentError => e
@status = 400
rescue StandardError => e
@status = 500
end
json_response({ success: false, message: @message || e.class.to_s, errors: [{ detail: e.message }] }, @status) unless e.class == NilClass
end

注意:render_unprocessable_entity_reresponse和json_reresponse是自定义方法,您可以添加自己的方法来渲染json-reresponse

您可以使用api_error_handler gem。

将其包含在打包程序文件中:

gem "api_error_handler", "~> 0.2.0"

在应用程序控制器中,调用库。

class ApplicationController < ActionController::API
handle_api_errors(
# Error handling options go here if you want to override any defaults.
)
# ...
end

现在,如果你有一个这样的控制器:


class UsersController < ApplicationController
def index
raise 'SOMETHING WENT WRONG!!!'
end
end

当你到达这个端点时,你会看到这个响应

{
"error": {
"title": "Internal Server Error",
"detail": "SOMETHING WENT WRONG!!!"
}
}

状态代码将根据您遇到的错误类型设置为适当的状态代码。

有关如何配置错误响应的更多信息,请参阅gem的自述文件。

最新更新