How do you respond with JSON in a Rails API when you need to respond with error information?

StackOverflow https://stackoverflow.com/questions/23661333

  •  22-07-2023
  •  | 
  •  

سؤال

For example...

module Api
    module V1
        class SessionsController < ApplicationController
            respond_to :json
            skip_before_filter :verify_authenticity_token

            def create
                @user = User.find_by(email: params[:session][:email].downcase)
                if @user && @user.authenticate(params[:session][:password])
                    token = User.new_remember_token
                    @user.update_attribute(:remember_token, User.digest(token))
                    respond_with :api, :v1, _____________
                else
                    #error
                end
            end
        end
    end
end

The #error part of the code, if the user is not properly authenticated. What syntax do I need to properly convey to the caller that the authentication did not go through for example, or in other cases, maybe data was not saved?

هل كانت مفيدة؟

المحلول

Like CBroe said, respond with an appropriate status code, such as 400 or 403. You could do just that (using 'head' to return the status code only), or also add an error message in JSON format:

{ 'error' : 'Authorization failed' }

The client code will want to check the status code and possibly the 'error' key in the JSON response and handle it appropriately.

Examples to put at the end of your controller action (pick one):

return head(:bad_request)  # returns a 400 status code only

render :json => { :error => 'That was an invalid request' } # defaults to 200 status

render :json => { :error => 'Oops! Bad request' }, :status => 400 

The last example overrides the default status to make it a 400. In general, the status can be an integer like that, or a symbol like :not_found or :bad_request. Hope that helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top