JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources
Internal server error when validation fails on a join model
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 2.3k
- Forks
- 546
- PR merge metrics
- No merged PRs in 30d
Description
Hello!
I have a model with a has_many :through relationship and a couple of validations on the join model. Whenever the validations fail i get a 500 response, a 422 with a properly formatted jsonapi error response would be preferable. For now i've resorted to using custom exceptions and fail CustomException in the validations so it's catched properly, but that's not ideal.
Problem is, the shovel (<<) method in _create_to_many_links (https://github.com/cerebris/jsonapi-resources/blob/master/lib/jsonapi/resource.rb#L280) is triggering the model's save! immediately, so when it raises ActiveRecord::ValidationFailed it's not catched and interpreted as an internal server error.
Can this be solved, or is there a preferred approach to processing such exceptions?
I've added a failing spec that demonstrates this issue here: https://github.com/needto/jsonapi-resources/commit/928485a4ea071edf164e954496c06b0de314d555
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in lib/jsonapi/resource.rb at _create_to_many_links around line 280, where the issue reports that the join model is saved immediately. Run or inspect the failing spec from commit 928485a4ea071edf164e954496c06b0de314d555; done means validation failures produce a 422 response with a properly formatted JSON:API error response instead of a 500.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100