Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling with .post()

Tags:

jquery

I have to modify a project written by someone else. Because the code is a mess I can't really change this $.post() (or replace it by $.ajax()). What I need to do, is to know if the post returns something else then JSON and return it.

$.post('balbal.html', json, function(data) { ... my coude ... }, 'json') 

I can see the post response in the console.log. Is there a simple way to retrieve it?

like image 785
meo Avatar asked Apr 23 '10 10:04

meo


People also ask

How does REST API handle error response?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.

How do you handle errors in Fetch?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.

How do you handle errors with Axios?

axios. get('/user/12345') . catch(function (error) { if (error.


2 Answers

Define the error callback immediately after the post. Note the semi-colon placement only at the end.

$.post('balbal.html', json, function(data) {     // ... my code ... }) .fail(function(response) {     alert('Error: ' + response.responseText); }); 

http://api.jquery.com/deferred.fail/

For older versions of jQuery (pre-1.8) Use .error instead with the same syntax.

like image 148
hyprnick Avatar answered Oct 25 '22 23:10

hyprnick


There's a couple of ways to do it, but if you're not getting the error response available through the returned JSON data object, you can use $.ajaxSetup() to define defaults for all ajax calls through jQuery. Even though the $.post() method doesn't specify an error handler or callback in and of itself, the $.ajaxSetup() method will capture any ajax faults and execute the function you define for it.

Alternatively, there is also an $.ajaxError() function that will do the same sort of thing.

Note that this will not work if your JSON response is returned correctly but with a server-side error code. If you want to capture these sorts of cases, you might be best to look for them using the $.ajaxComplete() method

like image 24
Phil.Wheeler Avatar answered Oct 25 '22 22:10

Phil.Wheeler