Clean Errors Gem
This is a small utility gem that allows for typed errors with I18n lookup built in. It provides an easy to use framework for making well structured, meaningful errors without adding a ton of boilerplate to your ruby code.
Requirements
Requires Ruby 2.5 or greater. Requires I18n (included in Rails by default).
Installation
Add clean_errors to your Gemfile
gem 'clean_errors'
Usage
class PlainRubyClass
def do_something
obj = Object.find_by(id: 1)
return CleanErrors::ValidationError('ResourceNotFound') unless obj
obj
end
end
This will create a validation error that will look up the message in I18n config files and type it appropriately. You can also render this object as JSON and it'll work.
I18n
This will look up keys by "errors.#type" where the type is the value you pass in. It will then apply named substitions on the string and set it to the message.
JSON Representation
When you return a CleanError as JSON, it will render like this:
{
"type": "ResourceNotFound",
"message": "Resource User[14] was not found."
}
Named Substitutions
We use Ruby's built in string substition to make I18n more flexible. For example, we could have the I18n string set to
errors:
ResourceNotFound: "Resource %{resource} was not found"
And then have the caller pass in the named arguments
CleanErrors::ValidationError('ResourceNotFound', resource: 'Object[1]')
License
Copyright 2018 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.