t6d / smart_properties

Ruby accessors on steroids
MIT License
177 stars 20 forks source link

Use custom ArgumentError exception with metadata #7

Closed fabrik42 closed 10 years ago

fabrik42 commented 10 years ago

I want to use smart properties to validate/sanitize hashes. However, if this is connected to a user facing interface, you usually want to provide some kind of feedback, when the property interfaces are not satisfied.

So I added a custom exception class, called SmartProperties::ArgumentError, that has an additional property called errors. It contains a hash of the structure invalid_field => error explanation that can be used e.g. for rendering a JSON error response.

Please note that SmartProperties::ArgumentError inherits from ArgumentError to keep backwards compatibility.

Cheers!

t6d commented 10 years ago

Thanks for contributing. I implemented a modified version of your idea. Instead of using a single error class, I created a class for each type of error. To stay backwards compatible, these classes inherit from ::ArgumentError as you suggested. Instead of an #errors method, I implemented a #to_hash method for all error classes.

fabrik42 commented 10 years ago

Nice, thanks!