I have a submit function, which posts some data into a server and then the server returns a response. The function is working fine. I would like, though, to catch a couple of errors during the post process. For example, if there is no connectivity to the server, return an error to the user to inform him what's going on. instead of just pressing the button and do nothing. I know I can create a function to somehow ping the server and check if it's alive but that's not what I need. I would like to have a statement in the error function and catch most of the possible errors and output an explanation to the user.
$scope.submit = function() {
var link = 'http://app.example.com/api.php';
$http.post(link, {
username: $scope.data.username,
password: $scope.data.password
}).then(function(res) {
$scope.response = res.data;
$localStorage.token = res.data;
console.log($localStorage.token);
})
.catch(function(error) {
console.error(error);
})
.finally(function() {
//do something
});
};
Solution:
$http.post(link, {
username: md5.createHash($scope.data.username),
password: md5.createHash($scope.data.password),
}).then(function(res) {
//Success Scenario
})
.catch(function(error) {
if (error.statusText == ""){
$scope.response = "Unexpected error. Make sure WiFi is on."
//When the device is not connected on the internet the response error is -1 (or any number) and the statusText is empty. So we caching that one as-well.
}
else {
$scope.response = "Error - "+error.status + " ("+error.statusText+")";
//else we display the error along with the status, for example error 500 Internal Server error.
}
})
.finally(function() {
//This function will always be called at the end. Take advantage of it :)
});
I hope it's gonna be useful for someone.
Related
I'm a little new to the Mean stack and I've been trying to experiment a bit with http requests with a mongo database that has a collection for storing feedback
I'm repeatedly getting an error of "Can't set headers after they're sent" in my console.
Here's the code for my function
module.exports.saveFeedback = function(req, res, callback) {
var newFeedback = new feedback();
newFeedback.overallAppExperience = req.body.overallAppExperience;
newFeedback.save(function(err, result) {
if (err) {
return callback(err, null);
} else {
return callback(null, result);
}
});
}
Here's the code for my route
app.post('/feedback', function(req,res){
feedback.saveFeedback(req,res, function(err,result){
if(err){
res.status(500).send(err);
return;
}
else{
res.status(200).send(result);
return;
}
});
});
Here's the code for my controller
angular.module('myApp')
.controller('feedbackController', ['$scope', '$http', function($scope,
$http){
$scope.overallAppExperience=null;
$scope.feedbackSubmit=function()
{
var data={
overallAppExperience:$scope.overallAppExperience
}
$http.post('/feedback', data)
.then(function(response){
console.log(response.data);
},function(response){
console.log(response);
})
}]);
Here's the issue - The entry I make via submitting the feedback form on the html page gets logged on to the mongo database. The same doesn't get displayed on the web console in my browser.
This is the entry in the web console and it corresponds to the error function being invoked in the promise.
Object { data: null, status: -1, headers: wd/<(), config: Object, statusText: "" }
Also, the error message in the console mentions these two lines as problematic:
One in my feedback Function (Line 8)
return callback(null,result);
And the other in my routes function (Line 8)
res.status(200).send(result);
I have read similar posts about such errors and all of them talk about something to do with the return statements. I've tried playing around with the return statements by removing them and adding them again. However, the same error persists.
Any help would be greatly appreciated.
I'm actually working on a webclient calling a REST service.
After my last question, the GET request is working now.
Now i want o implement a DEL request using angulars delete method.
In the following example is my service request implemented.
function ItemsService($http) {
this.$http = $http;
}
ItemsService.prototype = {
deleteFoo: function (id) {
this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});
}
}
module.exports = {
ItemsService: ItemsService
}
I added a button on the webpage with ng-click="$ctrl.deleteMe()".
The controller looks like the following example:
function Foo(ItemsService) {
this.itemsService = ItemsService;
}
Foo.prototype = {
deleteMe: function () {
console.log('delete now');
this.itemsService.deleteFoo(1).then(
response => {
console.log('gelöscht? ' + response);
}
);
}
};
If i now click on the button, nothing happens. In the network trace log in the dev tools in the browser i can't see a DEL request.
To test this REST service request, i run the JSON Server tool on port 3001.
I testet the availability of the server with SOAPUI, it works, i see all the requests in the console.
But no request from my test webpage.
Can anyone help me?
You need to return
return this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});
I'm using AngularJS v1.5.0. I'm on Chrome Version 55.0.2883.95. The error I'm seeing shows similar failure behavior to this SO post, although the error description for my situation just states Object.
I've created a plunker to demonstrate the error. Open the developer console at the plunker to see the resulting error.
Given the following service,
this.test = function() {
return $q(function(resolve, reject) {
var errorObject = {
httpStatusCode: 503,
error: {
code: 5030,
message: 'Oh no! Something went wrong, please try again'
}
};
reject(errorObject);
}).then(function successCallback(response) {
return response;
}).catch(function errorCallback(response) {
throw response;
});
};
AngularJS code generates the following error:
angular.js:13550 Object {httpStatusCode: 503, error: Object}
The AngularJS code in play is:
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args); // Error thrown on this line
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2 == null ? '' : arg2);
};
Here's how I call the service:
var test = function() {
userService.test()
.then(function successCallback(responseObject) {
console.log('Beginning of then');
})
.catch(function errorCallback(errorResponseObject) {
console.log('Beginning of catch');
});
}
The error seems to be caused by the fact that I am handling the promise rejection, and then re-throwing it. If I don't catch and rethrow, I don't get the error. Why do I receive the error when catching and re-throwing?
Update: It appears that using the $q service to reject the caught promise rejection avoids the AngularJS error I was seeing. I'll use that approach for now, but would still be interested to know why throwing out of the promise catch generates the error.
Example code without the error:
this.test = function() {
return $q(function(resolve, reject) {
var errorObject = {
httpStatusCode: 503,
error: {
code: 5030,
message: 'Oh no! Something went wrong, please try again'
}
};
reject(errorObject);
}).then(function successCallback(response) {
return response;
}).catch(function errorCallback(response) {
return $q.reject(response);
});
};
This question has nothing to do with AngularJS and much more on how promises work (including AngularJS's $q).
Throwing in a .catch is bound to have issues. Axel has an excellent explanation
if you want a quick and dirty method to get an exception to the console(or other logging mechanisms) you can use this trick:
.catch((err) => setTimeout(() => throw err));
Or its es5 variant:
.catch(function (err) { setTimeout(function () {throw err},0)})
This will keep the error as is, and get it out of the promise chain, without changing it.
However, I think it's better to incorporate the way that Axel explains in his article.
I've found what I believe to be the answer to my question. Buried in this discussion on the AngularJS Github issues section, #gkalpak notes the following:
The only difference between them is that return $q.reject(anything) will just pass anything down the chain, while throw anything will additionally pass anything to the $exceptionHandler. Other than that, both methods work the same.
So, the issue as far as I understand it, is that the $exceptionHandler prints the exception to the console. Using $q.reject as I stated in my update and again below does avoid this behavior and is my recommended solution to avoiding the console error.
this.test = function() {
return $q(function(resolve, reject) {
var errorObject = {
httpStatusCode: 503,
error: {
code: 5030,
message: 'Oh no! Something went wrong, please try again'
}
};
reject(errorObject);
}).then(function successCallback(response) {
return response;
}).catch(function errorCallback(response) {
return $q.reject(response);
});
};
Update - Based on #Sanders-Eias answer below, it is bad practice to throw exceptions out of async functions in general. That statement further bolsters the $q.reject approach.
On app launch it checks if a certain file exists, if not then it will make an http request to get an API in json format. If the request is successfully done, then it will create a json file.
The $cordova.writeFile() logs in success handler so it must have worked (I don't know how to check if it indeed made one though).
When I close the app and relaunch it then it checks again but it goes always in the error handler doesn't exist
// On launch
$scope.checkFile('news.json');
$scope.checkFile = function(file){
$cordovaFile.checkFile(cordova.file.dataDirectory, file)
.then(function (success) {
console.log('Exists!');
}, function (error) {
console.log('Doesnt exist');
$scope.update();
});
}
//If it doesn't exist
$scope.update = function () {
// Get all news
NewsService.getAllNews().then(function (data) {
$scope.saveFile('news.json', data);
$scope.news = data;
}, function (err) {
console.log(err)
});
};
// Write file
$scope.saveFile = function (file, data) {
console.log(file) // logs news.json
console.log(data) // logs data
$cordovaFile.writeFile(cordova.file.dataDirectory, file, JSON.stringify(data), true)
.then(function (success) {
// success
console.log('Worked!');
}, function (error) {
// error
console.log('Didn't work');
});
};
Edit:
cordova.file.dataDirectory leads to:
file:///data/user/0/com.myname.appname/files/
Is this the correct path?
Edit2:
Instead of logging my own error, I logged the variable error. It says:
FileError {code: 5, message: "ENCODING_ERR"}
I've read several of the other posts about this problem and none of the solutions seem to be working for me. I have the following code in my View:
this.model.set({
username: $('#user-username').val(),
role: $('#user-role').val(),
description: $('#user-description').val()
});
this.model.save({ user_id: this.model.get('user_id')}, {
success: function(user, response) {
console.log('success:', response);
$('.flash-message').text("Success").show();
},
error: function(user, response) {
console.log('error:', response);
$('.flash-message').text(response.error).show();
}
});
and this on my server controller (nodejs running express 3):
UserController.prototype.updateAction = function(req, res) {
if (req.route.method != "put") {
res.send({status: "error", error: "update must be put action and must include values"});
return false;
}
var query = {'user_id': req.params.id};
var user = req.body;
var userRepository = this.userRepository
// delete _id to avoid errors
delete user._id;
userRepository.update(query, user, {}, function(err, updated) {
if ((err) || (!updated)) {
res.send({"status": "error", "error": err});
return false;
}
// send updated user back
util.log('updated user ' + user.user_id);
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(JSON.stringify({"status": "success", "updated": updated}));
});
}
On save, my model is saved correctly in the server and I have verified the server response with this. So, as far as I can tell the server is returning status 200, valid JSON, with a valid JSON response header. And yet my backbone model.save function always triggers the error callback. Can anyone please tell me why and how to resolve this?
I am able to get this to work if set the dataType to text like so:
this.model.save({ user_id: this.model.get('user_id')}, {
dataType: "text",
success: function(user, response) {
console.log('success:', response);
$('.flash-message').text("Success").show();
},
error: function(user, response) {
console.log('error:', response);
$('.flash-message').text(response.error).show();
}
});
but doing so does not allow me to get the response back from the server. Instead I get this in the response var:
success: {
"_id": "5133b02062e15ed1d2000001",
}
Backbone expects to get back the model that it sent in its PUT or POST request body.
Instead of:
res.send(JSON.stringify({"status": "success", "updated": updated}));
Try this in your server's response:
res.json(user);
There may be a possibility that your call may have got in state 200 connection established which backbone detects as error, Backbone throws success only when the call is 200OK.
What's your server code? You need to make sure you're sending json back to backbone like so:
//In your express POST route
user.save(function(err) {
if(err){
console.log(err);
return res.json(401);
} else {
console.log('user: ' +user.username + ' saved');
return res.json(200);
}
Then in your backbone view you can check for the response and do what you need:
//some function in your view
this.model.save(this.formValues, {
success: function(model, response, options) {
if (response == 200) {
console.log('success :' + response);
//Do stuff
} else {
console.log('error: '+response);
//etc.
Also note that as per the backbone model documentation:
"save accepts success and error callbacks in the options hash, which will be passed the arguments (model, response, options)"