我正在使用NodeJS
和Express
创建一个服务,该应用程序封装了api Instagram,并且很多时候它们都会出现异常,因为用户必须使用流程。
我试图在try / catch中包含我的动作代码,但是当应用程序抛出一个expcetion时,npm停止工作,我必须执行:
$ npm start
为了让我的应用程序运行,我找不到允许应用程序在发生错误后仍然运行的解决方案。
我知道当前的错误正在发生,因为我的mysql处于脱机状态但在类似情况下我想返回捕获结果。
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
// all environments
app.set('port', process.env.PORT || 4300);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
//if ('development' == app.get('env')) {
app.use(express.errorHandler());
//}
/*------------------------------------------
connection peer, register as middleware
type koneksi : single,pool and request
-------------------------------------------*/
app.get('/', routes.index);
app.get('/home', routes.home);
app.get('/media/:id', routes.media);
app.get('/produto/:id', routes.produto);
app.get('/authorize_user', routes.authorize_user);
app.get('/handleauth', routes.handleauth);
app.use(app.router);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
function errorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
}
res.status(500);
res.render('error', { error: err });
}
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' });
} else {
next(err);
}
}
function logErrors(err, req, res, next) {
console.error(err.stack);
next(err);
}
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
/*
* GET home page.
*/
var mysql = require('mysql');
var ig = require('instagram-node').instagram();
var request = require("request")
var userinfos = { host: 'localhost', user: 'root', password : 'root', port : 8889, database:'bluebird' };
var auth = '';
var redirect_uri = 'http://localhost:4300/handleauth';
ig.use({
client_id: 'xxxxxxxxxx',
client_secret: 'xxxxxxxxxxxx'
});
exports.index = function(req, res){
res.render('index', {
title: 'Blue Bird API',
content: 'Integração com o instagram'
});
};
exports.home = function(req, res){
try {
var con = mysql.createConnection(userinfos);
con.query('SELECT * FROM home',function(err,rows){
if(err) throw err;
var result = [];
rows.forEach(function(value, index, ar){
ig.use({ access_token: auth });
ig.media(value.Image, function(err, media, remaining, limit) {
if(!err)
result.push(media);
if(index + 1 >= rows.length){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.json(result);
}
});
});
});
} catch(err) {
res.json([]);
}
};
exports.produto = function(req, res){
try {
var id = req.params.id;
var con = mysql.createConnection(userinfos);
con.query('SELECT * FROM Produto where Product = id',function(err,rows){
if(err) throw err;
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.json(rows);
});
} catch(err) {
res.json([]);
}
};
exports.media = function(req, res){
try {
var id = req.params.id;
var url = "https://api.instagram.com/oembed/?url=http://instagram.com/p/" + id;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.json(body); // Print the json response
//var results = JSON.parse(body);
}else {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send(response);
}
});
} catch(err) {
res.json([]);
}
};
exports.authorize_user = function(req, res) {
try {
res.redirect(ig.get_authorization_url(redirect_uri, { scope: ['likes'], state: 'a state' }));
} catch(err) {
res.json([]);
}
};
exports.handleauth = function(req, res) {
try {
ig.authorize_user(req.query.code, redirect_uri, function(err, result) {
if (err) {
console.log(err.body);
res.send("Didn't work");
} else {
console.log('Yay! Access token is ' + result.access_token);
auth = result.access_token;
res.send('You made it!!');
}
});
} catch(err) {
res.json([]);
}
};
/Users/felipeassuncao/Development/Projects/bluebird/api/routes/index.js:28
if(err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:8889
at Object.exports._errnoException (util.js:896:11)
at exports._exceptionWithHostPort (util.js:919:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1073:14)
--------------------
at Protocol._enqueue (/Users/felipeassuncao/Development/Projects/bluebird/api/node_modules/mysql/lib/protocol/Protocol.js:110:48)
at Protocol.handshake (/Users/felipeassuncao/Development/Projects/bluebird/api/node_modules/mysql/lib/protocol/Protocol.js:42:41)
at Connection.connect (/Users/felipeassuncao/Development/Projects/bluebird/api/node_modules/mysql/lib/Connection.js:99:18)
at Connection._implyConnect (/Users/felipeassuncao/Development/Projects/bluebird/api/node_modules/mysql/lib/Connection.js:298:10)
npm ERR! Darwin 15.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.0.0
npm ERR! npm v3.8.6
npm ERR! code ELIFECYCLE
npm ERR! application-name@0.0.1 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the application-name@0.0.1 start script 'node app.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the application-name package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs application-name
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls application-name
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /Users/felipeassuncao/Development/Projects/bluebird/api/npm-debug.log
答案 0 :(得分:1)
致命错误(如连接错误)会传播到所有待处理的回调。这意味着您无法在try-catch
块中处理此类错误。
要处理连接错误,您需要在连接对象上调用connect
方法并提供回调来处理错误:
con.connect(function (err) {
console.log(err); // the connection error
});
您需要在try-catch
块之外定义连接对象。您可以在the node-mysql documentation