How to catch a 401 (or other status error) in an angular service call? - rest

Using $http I can catch errors like 401 easily:
$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}).
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
if(status == 401)
{
alert('not auth.');
}
$scope.posts = {};
});
But how can I do something similar when using services instead. This is how my current service looks:
myModule.factory('Post', function($resource){
return $resource('http://localhost/Blog/posts/index.json', {}, {
index: {method:'GET', params:{}, isArray:true}
});
});
(Yes, I'm just learning angular).
SOLUTION (thanks to Nitish Kumar and all the contributors)
In the Post controller I was calling the service like this:
function PhoneListCtrl($scope, Post) {
$scope.posts = Post.query();
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
As suggested by the selected answer, now I'm calling it like this and it works:
function PhoneListCtrl($scope, Post) {
Post.query({},
//When it works
function(data){
$scope.posts = data;
},
//When it fails
function(error){
alert(error.status);
});
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];

in controller call Post like .
Post.index({},
function success(data) {
$scope.posts = data;
},
function err(error) {
if(error.status == 401)
{
alert('not auth.');
}
$scope.posts = {};
}
);

Resources return promises just like http. Simply hook into the error resolution:
Post.get(...).then(function(){
//successful things happen here
}, function(){
//errorful things happen here
});
AngularJS Failed Resource GET

$http is a service just like $resource is a service.
myModule.factory('Post', function($resource){
return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'});
});
This will return the promise. You can also use a promise inside your factory and chain that so your factory (service) does all of the error handling for you.

Related

how to update state variables inside prepareheaders in rtk query

I start to use RTK query and try to update headers with new access tokens but found it's hard to update the access in state. More specifically, there is no way to access dispatch inside prepareHeaders. Only getState is exposed.
createApi({
reducerPath: 'baseApi',
baseQuery: fetchBaseQuery({
baseUrl: "/",
prepareHeaders: (headers, { getState } ) => {
const { token, expiration } = getState().auth
if (expiration > new Date()) {
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
} else {
// if token expired, get a new token
try {
const result = await fetch("/token_store")
//dispatch(setNewToken(result)) ---> how to use dispatch here?
} catch (err) {
console.log("something goes wrong.")
}
}
return headers
}),
endpoints: () => ({}),
});
You should definitely not do that in prepareHeaders - there is a reason why there is no dispatch available there.
For something like that, you would wrap your baseQuery.
There are some examples of wrapping the basequery here in the documentation

How to get axios error response INTO the redux saga catch method

With axios the code is:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => err);
}
And then I'm using this with redux-saga like this:
function* createBlaBlaFlow(action) {
try {
const response = yield call(createBlaBla, action.payload);
if (response) {
yield put({
type: CREATE_BLA_BLA_SUCCESS
});
}
} catch (err) {
// I need the error data here ..
yield put({
type: CREATE_BLA_BLA_FAILURE,
payload: 'failed to create bla-bla'
});
}
}
In case of some error on the backend - like invalid data send to the backend - it returns a 400 response with some data:
{
"code":"ERR-1000",
"message":"Validation failed because ..."
"method":"POST",
"errorDetails":"..."
}
But I don't receive this useful data in the catch statement inside the saga. I can console.log() the data in the axios catch statement, also I can get it inside the try statement in the saga, but it never arrives in the catch.
Probably I need to do something else? ... Or the server shouldn't return 400 response in this case?
So, I came up with two solutions of this problem.
===
First one - very dump workaround, but actually it can be handy in some specific cases.
In the saga, right before we call the function with the axios call inside, we have a variable for the errors and a callback that sets that variable:
let errorResponseData = {};
const errorCallback = (usefulErrorData) => {
errorResponseData = usefulErrorData;
};
Then - in the axios method we have this:
export const createBlaBla = (payload, errCallback) => {
return axios.post('/some-url', payload)
.then(response => response)
.catch(err => {
if (err && err.response.data && typeof errCallback === 'function') {
errCallback(err.response.data);
}
return err;
});
}
This way, when we make request and the backend returns errors - we'll call the callback and will provide the errors from the backend there. This way - in the saga - we have the errors in a variable and can use it as we want.
===
However, another solution came to me from another forum.
The problem I have is because in the method with the axios call I have catch, which means that the errors won't bubble in the generator. So - if we modify the method with the axios call like this:
export const createBlaBla = (payload) => {
return axios.post('/some-url', payload)
}
Then in the catch statement in the saga we'll have the actual backend error.
Hope this helps someone else :)
In your API call you can do the following:
const someAPICall = (action) => {
return axios.put(`some/path/to/api`, data, {
withCredentials: true,
validateStatus: (status) => {
return (status == 200 || status === 403);
}
});
};
Please note the validateStatus() part - this way when axios will encounter 200 or 403 response, it will not throw Error and you will be able to process the response after
const response = yield call(someAPICall, action);
if (response.status === 200) {
// Proceed further
} else if (response.status === 403) {
// Inform user about error
} else {
...
}

Sailsjs external module not working in service

I'm using restler (https://github.com/danwrong/restler) to make api calls from an external source. In Sailsjs, from what I understand, helper functions are called services. I put the restler code for get, post, etc in their own services so I wouldn't repeat myself with the same code over and over again. However, the restler functions that worked fine in my controller no longer worked in the service. For instance:
//api/services/myService.js
module.export{
httpGet: function(){
var rest = require('restler');
rest.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
console.log('Error:', result.message);
this.retry(5000); // try again after 5 sec
} else {
console.log(result);
}
});
}
}
I know my service is being used correctly; I've tried returning a variable from the service to double check:
httpGet: function(){
var check = null;
var rest = require('restler');
rest.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
check = false;
console.log('Error:', result.message);
this.retry(5000); // try again after 5 sec
} else {
console.log(result);
check = true;
}
});
return check;
//in the controller, myService.httpGet() returns null, not true or false
}
Any help would be very appreciated. Salisjs v0.12.4
It would be better to make the service to accept a callback.
//api/services/myService.js
module.exports = {
httpGet: function(callback){
var rest = require('restler');
rest.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
console.log('Error:', result.message);
return callback(result, null)
//this.retry(5000); // try again after 5 sec
} else {
console.log(result);
return callback(null, result)
}
});
}
}
Then from your controller pass a callback when calling the service
myService.httpGet(function callback(err, result){
// handle error
// use result
})
Moreover regarding your question, you are returning return check; from service early with the value null you assigned to it.
PS: You can use promises instead of using callback( callback hell )
You should export the httpGet function as a property of the module object. Basically, you've got a "small" typo. Instead of this:
module.export{
httpGet: function(){
you should have this:
module.exports = {
httpGet: function(){
And also, if you want to return the result, add a callback:
module.exports = {
httpGet: function(callback){
...
if (result instanceof Error) {
console.log('Error:', result.message);
return callback(result, null)
} else {
console.log(result);
return callback(null, result)
}
...
... or use Promises.

Angular2 Stripe integration stripeResponseHandler cannot access this

I'm integrating Stripe payments with Angular2 (actually Ionic but the code is the same)
the call to Stripe.card.createToken is successful and returns a token
but in stripeResponseHandler which is an async callback, I cannot access any of the "this" variables. for example I cannot set this.amount = 10 and I cannot call this._http.post
how can I access the "this" variables ? I'm trying to http post the token and the amount to an API to make the payment
constructor(private _navController: NavController,
private _http: Http) { }
submitPayment() {
Stripe.setPublishableKey(this.key);
this.card = new Card();
this.card.number = this.cardNumber;
this.card.cvc = this.cardCVC;
this.card.exp_month = this.cardExpMonth;
this.card.exp_year = this.cardExpYear;
this.card.address_zip = this.cardAddressZip;
try {
Stripe.card.createToken(this.card, this.stripeResponseHandler);
}
catch (e) {
alert(e.message);
}
// Prevent the form from being submitted:
return false;
}
stripeResponseHandler(status, response) {
if (response.error) { // Problem!
alert(response.error);
} else { // Token was created!
// Get the token ID:
alert(response.id);
try {
this.amount = 10;
let payment = new Payment();
payment.token = response.id;
payment.amount = this.amount;
let body = JSON.stringify(payment);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this._http.post(this.url, body, options)
.map(res => res.json())
.catch(this.handleError);
}
catch (e) {
alert(e.message);
}
}
}
handleError(error: Response) {
// may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
alert('error' + error.text + " " + error.statusText);
return Observable.throw(error.json().error || 'Server error');
}
If you just pass the function reference, then JavaScript doesn't keep the this reference. You have to take care of this explicitely:
Instead of
Stripe.card.createToken(this.card, this.stripeResponseHandler);
use
Stripe.card.createToken(this.card, (status, person) => this.stripeResponseHandler(status, person));
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
or
Stripe.card.createToken(this.card, this.stripeResponseHandler.bind(this));

How to use the login credentials with php in ionic project

I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});