Ok you can probably tell I'm a bit new to this Node js lark but I've been stumped on this for a while and I have searched high and low for an answer I can understand.
I created a simple json serving Twitter server for some tests (which I call with /tweets.json?search=SOMETHING and works fine), but I don't know how to stop this app crashing when Twitter responds with an error.
Obviously if the query string is not in the url or there's any other issue from the Twitter API there'll be an error, but how can I stop this incredibly simple app from crashing every time that happens?
I know this is probably very basic so big apologies in advance.
var Twit = require('twit');
var express = require("express");
var app = express();
var T = new Twit({ XXXXX KEYS XXXXXX });
app.get("/tweets.json", function(req, res) {
T.get('search/tweets', { q: req.query.search, count: 100, result_type: 'popular' }, function(err, reply) {
if(err){
res.jsonp(err);
}
res.jsonp(reply);
})
});
app.listen(process.env.PORT || 3000);
console.log("listening on port 3000");
You have a double callback. This bit:
if (err) {
res.jsonp(err);
}
res.jsonp(reply);
calls res.jsonp
both times when there is an error. To correct that part you need to put a return in the branch:
if (err) {
return res.jsonp(err);
}
res.jsonp(reply);
res.jsonp
is the wrong method for returning an error too. Perhaps something like:
if (err) {
return res.send(500, err.message); // Status code 500 with a message.
}
res.jsonp(reply);
Would be better.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments