Ryzal Yusoff
Ryzal Yusoff

Reputation: 1047

Should I worry about this 422 (Unprocessable Entity) error? (Rails & Devise)

I am using ajax to submit my registration form.

enter image description here

The form submitted correctly when the details are correct. I also able to capture the errors correctly if the details are wrong. But, if the details are wrong, I also could see POST http://localhost:3000/users 422 (Unprocessable Entity) error message on my console log :

enter image description here

My question is, should i be worried about this error? Or this is normal? If this is not normal, how should I correctly handle it?

Thanks!

################################ UPDATE ##############################

Error message from terminal:

Started POST "/users" for ::1 at 2016-06-15 09:20:20 +0100
Processing by RegistrationsController#create as JSON
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"0D1qSK8IfbuefQ0bwEdKQFD+6WZ8XJtCnl2FZ6Nln9khLtv6qYCmoTKhwBFkVIJdYXSRQJ4e+9QAAdJ5UJzukQ==", "user"=>{"first_name"=>"John", "last_name"=>"Doe", "email"=>"[email protected]", "password"=>"[FILTERED]"}, "commit"=>"Sign up"}
   (0.2ms)  BEGIN
  User Exists (0.6ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY '[email protected]' LIMIT 1
   (0.2ms)  ROLLBACK
Completed 422 Unprocessable Entity in 93ms (Views: 0.4ms | ActiveRecord: 1.1ms)

Registration controller:

class RegistrationsController < Devise::RegistrationsController
  respond_to :json

  def create
    super
  end
end

application.js:

$(function(){

  $("form#ajax_signup").submit(function(e){
     e.preventDefault(); 
     var user_info = $(this).serializeObject();
     console.log("About to post to /users: " + JSON.stringify(user_info));
     $.ajax({
       type: "POST",
       url: "http://localhost:3000/users",
       data: user_info,
       success: function(json){
         console.log("The Devise Response: " + JSON.stringify(json));
       },
       error: function(xhr) { 

            var errors = jQuery.parseJSON(xhr.responseText).errors; 

            for (messages in errors) { 
                error_messages =  messages + ' ' + errors[messages];

                console.log(error_messages);
            } 

       }, 
       dataType: "json"
     });
  });

});

Upvotes: 0

Views: 2585

Answers (1)

nikolayp
nikolayp

Reputation: 17929

No you don't worry about 422 in your console, this red warning will not break your javascript code. But this error can provide you easy validation handling in your javascript code, like:

$('#form').on('ajax:error', 
  function () { return 'handle me'; }
);

Upvotes: 1

Related Questions