0

I'm a bit confused by the output in my rails console, and that a Rails API only project is returning HTML errors. I have a controller that is throwing an ActiveRecord Validation Error. In my console output I see:

  ↳ app/controllers/v1/users/accounts_controller.rb:7:in `create'
Completed 422 Unprocessable Entity in 324ms (ActiveRecord: 30.9ms | Allocations: 15443)

ActiveRecord::RecordInvalid (Validation failed: Password is too short (minimum is 8 characters)):

app/controllers/v1/users/accounts_controller.rb:7:in `create'

But in the response I'm getting a huge chunk of HTML. These routes are wrapped in scope :v1, defaults: { format: :json } do so I would expect the response format to be JSON. Is this expected behavior?

Yes I plan to catch errors and handle them, but I'm confused why a rails API only application would return any html.

Rails 7.0.2.2 Ruby 3.0.3

hummmingbear
  • 2,294
  • 5
  • 25
  • 42
  • You probaly shouldn't be using `create!` or `save!` in your controller. Invalid user input is not an exceptional event and shouldn't be treated as such - the bang methods should be reserved for contexts where it should not be expected to fail, or inside of a transaction to trigger a rollback. There are also better ways to dry the code like for example using the Responders gem instead of `rescue_from`. – max Feb 18 '22 at 13:45
  • 1
    Could the HTML response be that you're in the development environment and that its the default error page being rendered? That behavior is determined by [`config.consider_all_requests_local`](https://stackoverflow.com/questions/373089/purpose-of-consider-all-requests-local-in-config-environments-development-rb) and its still the default in an api only app. – max Feb 18 '22 at 13:50
  • @max thanks for the advice, that is not how my production controllers looks. I was intentionally causing an error for this example. You are exactly right, `consider_all_requests_local` was the issue. Setting that to false gives me a JSON error response. Weird they would still spit out HTML in development on an API only application. Feel free to post it as an answer and I will select it. – hummmingbear Feb 18 '22 at 15:02

1 Answers1

0

As @max pointed out, HTML errors were being returned due to consider_all_requests_local being set to true in development.rb. You can read more about that here. Seems counterintuitive to return HTML responses in API only mode, alas setting it to false will correct the issue.

hummmingbear
  • 2,294
  • 5
  • 25
  • 42