0

The question is simple: return an error from a controller as JSON response:

//controller
def action1
   # .....
   return render(json: { status: :unprocessable_entity }) if !is_my_valid?
   # .... doing something
   render(json: my_hash.to_json)  

end
//view
$.ajax({
  url: 'some_url',
  //...
}).done(function(data) {
  // it always gets here even in case of an error

}).fail(function(jqXHR, textStatus) {
  alert("error: " + textStatus);
});

So the problem is that on the HTML page, even in case of an error, the callback function in .done() is executed, not the one in .fail(). How do I make it into .fail()?

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58

1 Answers1

3

Send back a 500 HTTP status code:

render(json: { ... }, status: 500)  
Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
  • well, it's working, how do I also send the error message so it'll be shown in `fail` by alert? –  Nov 19 '14 at 10:12
  • @Grienders You would have to add that error message to the JSON, and then retrieve it inside the `.fail()`. – Nabil Kadimi Nov 19 '14 at 10:19
  • `}).fail(function(data) { alert("error: " + data.responseText + " status: " + data.status); });` -- this will show error message and status of error. – Yevgeniy Anfilofyev Nov 19 '14 at 10:29