Is there a way to ignore or bypass this error code 400 and just trigger a function when this error occurs?
I tried this : --
vm.createOrder = function () {
var deferred = $q.defer(); // update
orderService.createOrder()
.then(function (response, status) {
deferred.resolve(response); // update
if(status == 400) {
console.log('Should never happen but trigger a function anyway! ');
localStorage.clear();
}
console.log('Successfully created an order: ', response.status);
})
}
orderService: --
createOrder: function () {
return $http({
url: 'apiURL',
method: 'POST'
})
}
but it doesn't even console.log the string in the if(status) condition or in the success, but the POST method does go through so its posting the data I want to post but it returns an error code of 400.
Edit fixed
orderService.createOrder()
.then(function (response) {
console.log('Successfully created an order: ', response.status);
})
.catch(function (e) {
console.log('Should never happen but trigger a function anyway! ');
localStorage.clear();
console.log(e);
})
Your service should look like this.
createOrder: function () {
return $http.post('SomeURL')
.then(function (response) {
return response.data;
},
function (response) {
return $q.reject(response);
});
}
You should call it like this, rather than a try catch.
orderService.createOrder().then(function(response){
//Successfull Call
},function(response){
//Error on call
});
Related
I am trying to use fetch and post methods to change a value. This all works fine. My problem is moving on after the fetch (in this example, I want to post a simple "ok"). The problem is that it never actually gives me that message. It gives me the "error" message, when I change to a wrong API.
async function sendCon(number) {
let data = JSON.stringify(number);
console.log("I accept")
await fetch(acceptAPI, {
method: 'POST',
body: data
}).then(function() {
console.log("ok");
}).catch(function() {
console.log("error");
})
}
Please help, I've been trying to figure this out for three days.
Thanks
You can assign the response to a variable and check if the response has a status code of 200.
async function sendCon(number) {
try {
let data = JSON.stringify(number);
const response = await fetch(acceptAPI, {
method: "POST",
body: data,
});
if (response.status === 200) {
console.log("ok");
} else {
console.log("error");
}
} catch (error) {
console.log(error);
}
}
I am trying to call a odata end Point and check the response and make a another call to different endpoint if the condition is not met. If I don’t have the condition and making just one call to just one end point it works, but below code is throwing Reference error even with the attempt to the first call
$scope.getRequest = function () {
var url = $rootScope.BaseURL;
var config = {
headers: {
'Authorization': `Basic ${$scope.key}`,
'Prefer': 'odata.maxpagesize=2000'
}
};
$http.get(url, config)
.then(
function (response) { // success async
$scope.viewRequest.data = response.data;
},
function (response) { // failure async
console.log("There was an error getting the request from CORE");
}
);
if (viewRequest.data.REV_SAMPLE_CMQREQUEST.length = 0) {
var url = $rootScope.BaseURL + `CMQ_REQUEST('${$scope.viewRequest.barcode}’)`;
var config = {
headers: {
'Authorization': `Basic ${$scope.key}`,
'Prefer': 'odata.maxpagesize=2000'
}
};
$http.get(url, config)
.then(
function (response1) { // success async
$scope.viewRequest1.data = response1.data;
},
function (response1) { // failure async
console.log("There was an error getting the request from CORE");
}
);
}
};
Below is the screenshot of the error
$scope.getRequest = function () {
var url = $rootScope.BaseURL;
var config = {
headers: {
'Authorization': `Basic ${$scope.key}`,
'Prefer': 'odata.maxpagesize=2000'
}
};
$http.get(url, config)
.then(function (response) { // success async
$scope.viewRequest.data = response.data;
},
function (response) { // failure async
console.log("There was an error getting the request from CORE");
}
)
.then(nextViewRequest);
};
var newViewRequest = function (response) {
var url1 = $rootScope.BaseURL + `CMQ_REQUEST('${$scope.viewRequest.barcode}')`;
if ($scope.viewRequest.data.REV_SAMPLE_CMQREQUEST.length = 0) {
return $http.get(url1, config)
.then(
function (response1) { // success async
$scope.viewRequest1.data = response1.data;
},
function (response1) { // failure async
console.log("There was an error getting the request from CORE");
}
);
}
return $q.reject({ message: 'Validations didnt work' });
};
You are making 2 request in parallel rather than wait for the first one to finish and then make the second one, also the code is hard to read. My guess is that the second response is not returning anything because the first condition is not met.
I recommend you to read about promises chaining and the $q service to make custom rejections or resolve promises in your scenarios to order this logic your code should like something like this:
$scope.getRequest = function () {
// setup url and config
$http.get(url, config)
.then(nextViewRequest) // the return of this function will override the next result of the next promise chaining
.then(function(response) {
$scope.viewRequest1.data = response.data;
});
};
var nextViewRequest= function(response) {
// validations necessary
if(valid) {
return $http.get(url, config);
}
// If conditions are not met, then you can use the $q service to create a rejection
return $q.reject({message: 'validations on second request failed'});
};
I have a function which uses jquery to call API and get a result. My API end is programmed to return the number "19" just for testing.
export function clientAdd(data) {
return (dispatch) => {
return $.ajax({
url: "http://api.example.com/client/add/",
headers: {'AUTHORIZATION': `${sessionStorage.jwt}`},
type: 'POST',
cache: false,
data: data,
dataType: 'json',
success: function (data) {
let redirectUrl = '/client/' + data
return redirectUrl';
},
error: function(xhr, status, err) {
if (xhr.status === 401) {
sessionStorage.removeItem('jwt');
return '/signin';
}
console.log('xhr',xhr.responseText);
console.log('status',status);
console.log('err',err);
return dispatch({type: GET_CLIENT_FAIL, err});
}
})
}
}
Then in my component, upon clicking on the submit button, it will call the onSave function as follows
onSave(event) {
//event.preventDefault();
this.props.actions.clientAdd(this.state.credentials).then((result) => {
return this.setState({redirect: true, newCustomerId: result})
}).catch((result) => {
return this.setState({redirect: false, errorMessage: result})
});
}
Where the result is supposed to be the redirectUrl or ErrorMessage.
However, I'm keep getting the number 19 which is returned by my API.
I read online if I want to use promise in my component, i have to add return infront of $.ajax, if not "then" will be undefined.
What you can do is, create your own promise and put the ajax call inside it
Then call resolve and pass data that you want when then is called
resolve(data_passed_to_then)
Like this :
return new Promise((resolve,reject) => {
$.ajax({
...
success: function (data) {
let redirectUrl = '/client/' + data
resolve(redirectUrl);
},
error: function(xhr, status, err) {
...
// return dispatch({type: GET_CLIENT_FAIL, err});
reject(err);
}
})
})
I am trying to catch server error for eg 500 in my angular app. Unfortunately this construction fails:
return promise = this.httpService.jsonp("serverurl")
.success((response: any): ng.IPromise<any> => { return response.data; })
.error((response: any): ng.IPromise<any> => { return response.data; });
I want to catch server response - in this case simply the message. How to do this?
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(response); // add console log of response
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(response); // add console log of error response
});
Or a interceptor can be used to "monitor" all http's:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
I am trying the following code in an angular.js application to migrate data from one database to another. This is one part of the function in order to gain authorization credentials to send POSTs to the receiving database. However, it doesn't work. My first function, ATsintegrationsService.beginBackfill(clientIDs), returns the list of applicants fine. The error begins at getAuthToken(). Even though it hits the URL with the correct data, I keep on getting an error in the service. Can anyone shed some light on what is going on here, I'd really appreciate it. I'm at a loss for what may be causing my issues.
Main function (triggered by hitting an apply button):
$scope.beginBackfill = function() {
$scope.loading = true;
AtsintegrationsService.beginBackfill($scope.clientids).then(function (response) {
$scope.applicants = response.data;
$scope.getAuthToken();
$scope.createSuccess = true;
$scope.loading = false;
},
function(error) {
$scope.loading = false;
$scope.createFailure = true;
console.log("Failure to backfill data - " + error);
});
};
Here is $scope.getAuthToken():
$scope.getAuthToken = function() {
AtsintegrationsService.getAuthToken().then(function (response) {
$scope.authToken = response.data;
console.log($scope.authToken);
},
function(error) {
$scope.loading = false;
$scope.createFailure = true;
console.log("Failure to obtain auth token - " + error);
console.log(error);
});
};
And finally, the service code for getAuthToken() - some data has been removed and is indicated by {snip}.
srvc.getAuthToken = function () {
var url = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
responseType: 'json',
method: 'POST',
url: url,
data:
{
"grant_type": "{snip}",
"client_id": {snip},
"client_secret": "{snip}"
}
})
.success(function (data) {
console.log("We have a proper return.");
return data;
})
.error(function (data) {
console.log("There was an error in the service.");
return data;
});
};
We figured out the problem was with CORS headers; the code I have was fine.