Sending custom error message from Express JS over to Backbone - javascript

In express js, I have the following code which sends a response over to Backbone:
if (!user) {
req.session.messages = [info.message];
return res.send(400, howCanIsendTheErrorMessageAlso);
}
How can I send the error message also, together with the error code?
How can Backbone receive it?
Any ideas?
In backbone, I have the following code:
loginModel.save({
username : obj.elEmail.val(),
password : obj.elPassword.val(),
admin : false
}, {
success: function (e) {
console.log('success');
},
error: function (e) {
console.log(e);
}
});
Any ideas?

You send it from express with:
res.send(500, { error: "hi, there was an error" });
In Backbone the parameters of your error callback are: model, xhr, options
So you need to extract your error message fron the xhr object in the error callback like this:
obj.save(
{
data:"something"
},
{
success: function(model, response, options){
console.log("worked");
},
error: function(model, xhr, options){
console.log("error", xhr.responseText);
}
}
);

in your express app (for example):
res.send(403, {
error: "some elaborate error message"
});
Your Backbone code is correct, you'll see the error
regarding error codes, I would recommend sticking to this list http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Related

Handle exception in Node.js and send the error output to HTML

I have a function which console logs the error in case error exist, I wish to send the same data back to HTML <div>. The <div> must only load in case of error and present user with the error msg.
app.js
console.log('Pulling Image from DockerHub\n');
const result1 = cp.execSync('docker pull mongo:'+version);
console.log(result1.toString());
Let's say the above code generates an error and I wish to get the data on my HTML using jQuery AJAX.
index.html
<div id="errorReport"></div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
console.log(res);
}
});
});
</script>
Need to handle error exceptions in the above child process (app.js) and render the data on index.html ONLY if ERROR exists. If the cp doesn't return any error, no need to render any data on index.html
Update:
Let's say in here const result1 = cp.execSync('docker pull mongo:'+version); I give an incorrect value for version and the child process fails. As per the execSync syntax I cannot have a callback function to determine the error.
Now the console does display some error msg
Error response from daemon: manifest for mongo:a not found: manifest unknown: manifest unknown
child_process.js:660
throw err;
^
Now if I wish to display the same msg on my HMTL <div> what do I do?
The key is to catch the error on the server and return it in the HTTP response. You don't have to use .json({ ... }), but it tends to be convenient.
try {
cp.execSync(`docker pull mongo:'+version`);
res.status(200)
} catch (error) {
// catch the error and return it's message to the client
res.status(500).json({ error: error.message })
}
error.message tends to have the type of message you describe, but you can also access other fields like the stack trace, etc. Since the server is returning a statusCode 500, that will trigger the error callback, so you will need to add that handler to your request, then add the message to the DOM.
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
console.log(res);
},
error: function(xhr, textStatus, errorThrown) {
// parse the JSON from the server
const json = JSON.parse(xhr.responseText);
// finally, set the div's text to the error
$("#errorReport").text(json.error);
}
});
});
You can try this -
<div id="errorReport"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#errorReport").hide();
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
dataType:'json',
success: function(res, status) {
if(status === 500){
$("#errorReport").show();
}
console.log(res);
}
});
});
</script>
On your server -
try {
cp.execSync(`docker pull mongo:'+version`);
res.status(200)
} catch (error) {
//catch the error here and handle it accordingly by sending error response to client
res.status(500)
}

ParseError: 'bad or missing username'

So I have some cloud code I am trying to write to like a post.
My database is setup that users have a likedPosts array, which has object id's of all the posts that the user liked. Users also have a column coins, that should get incremented when users like their posts.
The post object has a likes column which is an integer that gets incremented with each like, and the post object also has a posterId column, which is the object id of the user that posted it.
Here is my function right now (I am not very good at javascript and cloud code, so if there is something horribly wrong, I'm sorry)
Parse.Cloud.define("likePost", function(request, response) {
Parse.Cloud.useMasterKey();
var senderId = request.params.senderId;
var postId = request.params.postId;
var post = new Parse.Object ({objectId: postId});
var posterId = post.posterId
var poster = new Parse.User ({objectId: posterId});
var sender = new Parse.User ({objectId: senderId});
sender.add("likedPosts", postId);
poster.increment("coins");
post.increment("likes");
poster.save(null, {useMasterKey:true, success:
function(poster) {
console.log("Successfully saved poster");
}, error: function(poster, error) {
console.error("Error saving poster: " + error.message);
response.error(error);
}
});
post.save(null,{useMasterKey:true, success:
function(post) {
console.log("Successfully saved post");
}, error: function(post, error) {
console.error("Error saving post: " + error.message);
response.error(error);
}
});
sender.save(null, {useMasterKey:true, success:
function(sender) {
console.log("Successfully saved sender");
}, error: function(sender, error) {
console.error("Error saving sender: " + error.message);
response.error(error);
}
});
response.success();
});
I call the function from swift like so:
PFCloud.callFunction(inBackground: "likePost", withParameters: ["senderId" : PFUser.current()!.objectId!, " postId": postObject!.objectId!], block: { (result, error) in
if (error != nil) {
print(error!)
} else {
print("success liking")
}
})
In my logs, however, I get the following error:
2017-06-21T21:47:59.499Z - Failed running cloud function likePost for user R4d8Zrcdhw with:
Input: {"senderId":"R4d8Zrcdhw"," postId":"XXbu55PdpR"}
Error: {"code":141,"message":{"code":200,"message":"bad or missing username"}}
2017-06-21T21:47:59.492Z - bad or missing username
My guess is that the request is missing a header to define the content-type. I've seen Parse return the "bad or missing username" error via the Parse REST API if the Swift URLSession was using an incorrect content-type header.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or
Parse.Cloud.httpRequest({
url: 'http://www.example.com/',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})

How to handle error in Angular Controller from MongoDB database update/delete in Express?

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?
I have the following route in Node/Express:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
//log the reason for the error
res.status(code || 500).json({
"error": message
});
}
app.delete("/polls/:id", auth, function(req, res) {
db.collection(POLLS_COLLECTION).deleteOne({
_id: new ObjectID(req.params.id), userID: req.user.id
//userID must match the req.user.id from Passport to make sure the poll belongs to the user
}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to delete poll");
} else {
res.status(204).end();
}
});
});
The following in an Angular JS controller:
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
alert("Error deleting poll");
console.log(response);
})
};
deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:
this.deletePoll = function(pollId){
var url = "/polls/" + pollId;
return $http.delete(url);
};
What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.
However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.
Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?
You can do like code below
Put this HTML code where you want to show error message :
<div style="color:red;">
{{error}}
</div>
In your angular js controller :
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
$scope.error="Any error message you like to show";
console.log(response);
})
};
If your API return an error. you can catch it like this :
Polls.deletePoll($routeParams.pollId).then(function(response) {
//SUCCESS CODE
}).catch(function(error) {
//NOTIFY ERROR
//NotifyService.display(error);
console.log(error);
});
thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:
if(err){
res.status(500).end();
}
if(result.deletedCount === 0){
res.status(404).end();
//error handling in Angular error callback
} else {
res.status(204).end();
//error handling in Angular success callback
}
});
});
this makes sure that not always a 204 is send whether or not the delete was successfull.

Twitter video upload with NodeJS

I am trying to post a video using Twitter modules in NodeJS but I am getting an error - Error 202 “Your credentials do not allow access to this resource”.
Here a snippet of code, it is missing the APPEND and FINISH calls etc but would have expected not to receive an error 202?
Has anyone managed to upload a video using JavaScript than can give me some guidance? I have tried to research and tried several different options.
T.post('media/upload', {
media: data,
encoding: 'base64',
command: 'INIT',
total_bytes: getFilesizeInBytes(image)
}, function(error, media, response) {
if (!error) {
var status = {
status: message
};
if(media) status['media_ids'] = media.media_id_string;
T.post('statuses/update', status, function(error, tweet, response) {
if(!error) console.log(' -- message sent');
else console.log(error);
});
} else {
console.log(error);
}
});

Parse.com cloud bad request 400

I use Parse.com cloud to manage my database for mobile application. When I save in table user some user with the same username or email it gives me the error:
POST https://api.parse.com/1/users 400 (Bad Request)
I understood by myself that error appears when the username or email are the same in different users. Is there a method to return the reason of the error like "this mail is already chosen"? Below my code:
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
alert("Save error");
console.log(error);
}
});
},
Looks like you aren't using response.error(error) anywhere...
Try
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
response.error(error);
}
});
}
And then in your native script console.log the error.code and error.message.

Categories

Resources