在error_codes.yml定义标准的API错误,包括status_code
,title
,details
和内部code
那么你可以用它来提供有关您的API文档的错误进一步信息。
这里有一个基本的例子:
api:
invalid_resource:
code: '1'
status: '400'
title: 'Bad Request'
not_found:
code: '2'
status: '404'
title: 'Not Found'
details: 'Resource not found.'
在配置/初始化/ api_errors.rb载荷YAML文件转换成一个常数。
API_ERRORS = YAML.load_file(Rails.root.join('doc','error-codes.yml'))['api']
对app/controllers/concerns/error_handling。RB定义一个可重用的方法来呈现的JSON格式的API错误:
module ErrorHandling
def respond_with_error(error, invalid_resource = nil)
error = API_ERRORS[error]
error['details'] = invalid_resource.errors.full_messages if invalid_resource
render json: error, status: error['status']
end
end
在您的API基本控制器包括关注所以它适用于所有从它继承控制器:
include ErrorHandling
你然后将能够在任何这些控制器上使用您的方法:
respond_with_error('not_found') # For standard API errors
respond_with_error('invalid_resource', @user) # For invalid resources
例如在您的用户控制器上,您可能有以下内容:
def create
if @user.save(your_api_params)
# Do whatever your API needs to do
else
respond_with_error('invalid_resource', @user)
end
end
的错误,你的API将输出看起来就像这样:
# For invalid resources
{
"code": "1",
"status": "400",
"title": "Bad Request",
"details": [
"Email format is incorrect"
]
}
# For standard API errors
{
"code": "2",
"status": "404",
"title": "Not Found",
"details": "Route not found."
}
当你的API的增长,你就可以轻松地在你的YAML文件,此添加新的错误代码,并利用它们方法避免重复,并使您的错误代码在整个API中保持一致。
你可以有一些控制器代码。它是API和你的应用程序请求相同的代码吗?因为您向我们展示了您对模型的验证,但我认为您应该在控制器上处理您的问题。 –