I’m currently debugging a REST API integration where my $.ajax calls are hitting the error callback. While I can see the status code (like 400 or 500), I’m struggling to capture the specific error message sent back by the server's payload. The errorThrown parameter only gives me a generic "Bad Request" string. How do I access the actual response body—specifically the JSON message—from the jqXHR object so I can display meaningful feedback to the user?
3 answers
To get the server's response text, you need to look inside the first argument of the error function, typically named jqXHR. This object contains a property called responseText. If your server returns JSON, you can parse it using JSON.parse(jqXHR.responseText). For example, in your error callback: error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); }. This will reveal the raw string sent by the server. It is best practice to always wrap this in a try-catch block just in case the response isn't valid JSON, which happens frequently with 500 Internal Server Errors.
Are you using a global ajax error handler like $(document).ajaxError(), or are you handling these locally within each individual request function?
You just need to use jqXHR.responseText inside the error block. If the API sends JSON, parse it to see the specific error field.
I agree with Dorothy. I usually check jqXHR.responseJSON first; some newer versions of jQuery actually pre-parse the error body for you if the Content-Type header is set correctly!
Michael, that's a great question because global handlers are much more efficient for enterprise apps. Steven, if you switch to $(document).ajaxError(), you get access to the same jqXHR object across your entire site. This allows you to write a single piece of logic that parses the responseText and triggers a notification toast. It saves you from repeating the same JSON.parse logic in every single $.ajax call you write, which is much better for long-term maintainability.