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.'
config/initializers/api_errors.rb YAML .
API_ERRORS = YAML.load_file(Rails.root.join('doc','error-codes.yml'))['api']
///error_handling.rb API JSON:
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')
respond_with_error('invalid_resource', @user)
, :
def create
if @user.save(your_api_params)
else
respond_with_error('invalid_resource', @user)
end
end
, API, :
{
"code": "1",
"status": "400",
"title": "Bad Request",
"details": [
"Email format is incorrect"
]
}
{
"code": "2",
"status": "404",
"title": "Not Found",
"details": "Route not found."
}
API YAML , API.