I'm writing REST API for application with Hanami ruby web framework, and I'm wondering how to set error format to JSON. For example,when 404 error occurred it should return response with body {'message': 'Method not found'}, and Content-Type: 'application/json'
Asked
Active
Viewed 607 times
1

Eyeslandic
- 14,553
- 13
- 41
- 54

Daniel Bober
- 23
- 6
2 Answers
1

Antarr Byrd
- 24,863
- 33
- 100
- 188
-
Option `format` works with controllers, but according to this page you may just rename 404 error template to 404.json.rb, and it works. Thank you – Daniel Bober Apr 16 '17 at 23:35
-
But where the `format: :json` should be placed? I also tried the solution with `404.json.slim` (I use Slim as a template engine) but it didn't help. – Aleksander Pohl Jan 09 '18 at 22:22
-
@AleksanderPohl You need to put this in your controller. There is no need for a template – Antarr Byrd Jan 09 '18 at 22:23
-
But how about an invalid path that causes 404? This solution won't work. – Aleksander Pohl Jan 10 '18 at 01:06
0
Stumbled upon this while searching for something else, so thought I'd answer it even though it's a really old question.
One quick way to do this would be to add a catch-all route at the very end of your routes. e.g.
# apps/web/config/routes.rb
get '/*', to: ->(env) { [404, { 'Content-Type' => 'application/json' }, ["Method not found"]] }
Since you're using Hanami, the http-router
configuration (where you could usually define a default_app
option) isn't available to you directly.
See lib/hanami/routing/default.rb
for the default "not found" action if you prefer to consider another approach with monkey-patching (or some way to supply a configuration option that I'm not aware of at this point).

Kenneth Teh
- 31
- 4