How to return content in 403 response in Rails?

When my controller action fails, I return 403 with some JSON data, so I can include error information (such as ActiveRecord errors). The problem is that the content of the response (as seen from the Chrome developer tools) seems empty.

Should I return 200, even if the requested action failed, and then check the JSON data in the "ajax: success" event handler? This seems a little strange. Ideally, I would like to access the data in the ajax: error handler.

I'm new to API style programming, so I don't know about best practices.

+4
source share
1 answer

I don't know if this is best practice or not, but I did it as follows:

In the controller, if an error occurs:

render :new, :status => :bad_request 

new.js.erb is the original view, including the form that displays errors.

JavaScript:

 $('#the_form').live('ajax:failure', function(evt, xhr, status, error) { if (xhr.status == 400) { alert(xhr.responseText); } else { alert('Generic error message'); } }); 

Rails sends 500 (: internal_server_error) when exceptions occur. This is described in JavaScript, but as you saw, you have no way to return an error or re-display the form in this case. I had to use a different status code to display the content, but still got into the ajax: failure event.

The following is a list of code mappings. I chose 400 because it was the closest match.

+3
source

Source: https://habr.com/ru/post/1333084/


All Articles