214214
215215## Parameter Validation and Coercion
216216
217- You can define validations and coercion options for your parameters using ` params ` .
217+ You can define validations and coercion options for your parameters using a ` params ` block .
218218
219219``` ruby
220220params do
@@ -260,22 +260,22 @@ end
260260
261261### Custom Validators
262262``` ruby
263- class doit < Grape ::Validations ::Validator
263+ class AlphaNumeric < Grape ::Validations ::Validator
264264 def validate_param! (attr_name , params )
265- unless params[attr_name] == ' im custom '
266- throw :error , :status => 400 , :message => " #{ attr_name } : is not custom! "
265+ unless params[attr_name] =~ /^ [[:alnum:] ]+$/
266+ throw :error , :status => 400 , :message => " #{ attr_name } : must consist of alpha-numeric characters "
267267 end
268268 end
269269end
270270```
271271
272272``` ruby
273273params do
274- requires :name , :doit => true
274+ requires :username , :alpha_numeric => true
275275end
276276```
277277
278- You can also create custom classes that take additional parameters
278+ You can also create custom classes that take parameters
279279``` ruby
280280class Length < Grape ::Validations ::SingleOptionValidator
281281 def validate_param! (attr_name , params )
@@ -292,6 +292,20 @@ params do
292292end
293293```
294294
295+ ### Validation Errors
296+ When validation and coercion erros occur an exception of type ` ValidationError ` is raised.
297+ If the exception goes uncaught it will respond with a status of 400 and an error message.
298+ You can rescue a ` ValidationError ` and respond with a custom response.
299+ ``` ruby
300+ rescue_from ValidationError do |e |
301+ Rack ::Response .new ({
302+ ' status' => e.status,
303+ ' message' => e.message,
304+ ' param' => e.param
305+ }.to_json, e.status)
306+ end
307+ ```
308+
295309
296310
297311## Headers
0 commit comments