Skip to content

Commit 1877069

Browse files
author
Sebastian Wilgosz
committed
Update README to incude information about handling validation errors
1 parent a4bce47 commit 1877069

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

README.md

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,47 @@ From this point you'll have default html errors being serialized. JsonapiErrorsH
4040

4141
If you rise any of errors above in any place of your application, client gets the nicely formatted error message instead of 500
4242

43+
### Handling unexpected errors
44+
45+
If you want to handle all the errors in your API application to deliver nicely formatted JSON response about 500 instead crashing the server, add this when your application loads:
46+
47+
```ruby
48+
require 'jsonapi_errors_handler'
49+
50+
JsonapiErrorsHandler.configure do |config|
51+
config.handle_unexpected = true
52+
end
53+
```
54+
4355
### Custom errors mapping
4456

4557
If you want your custom errors being handled by default, just add them to the mapper
4658

4759
```ruby
4860
include JsonapiErrorsHandler
4961
ErrorMapper.map_errors!({
50-
'ActiveRecord::RecordNotFound' => 'JsonapiErrorsHandler::Errors::NotFound',
51-
'ActiveRecord::RecordInvalid' => 'JsonapiErrorsHandler::Errors::Invalid',
62+
'ActiveRecord::RecordNotFound' => 'JsonapiErrorsHandler::Errors::NotFound'
5263
})
5364
rescue_from ::StandardError, with: lambda { |e| handle_error(e) }
5465
```
5566

56-
###Custom error logging
67+
### Handling rails-specific validation errors
68+
69+
To handle validation errors from ActiveRecord or ActiveModel, you need to write custom
70+
error handler:
71+
72+
```ruby
73+
rescue_from ActiveRecord::RecordInvalid, with: lambda { |e| handle_validation_error(e) }
74+
rescue_from ActiveModel::ValidationError, with: lambda { |e| handle_validation_error(e) }
75+
76+
def handle_validation_error(error)
77+
error_model = error.try(:model) || error.try(:record)
78+
mapped = JsonapiErrorsHandler::Errors::Invalid.new(errors: error_model.errors)
79+
render_error(mapped)
80+
end
81+
```
82+
83+
### Custom error logging
5784

5885
When you'll include the `jsonapi_errors_handler` to your controller, all errors will be handled and delivered to the client in the nice, formatted
5986
way.

0 commit comments

Comments
 (0)