简体   繁体   English

Express应用程序遇到错误时崩溃

[英]Express application crashes when it encouters an error

I'm creating a service using NodeJS and Express , that application encapsulates the api Instagram and many times they can thew an exception because the user have to use an flow. 我正在使用NodeJSExpress创建服务,该应用程序封装了api Instagram,由于用户必须使用流,因此它们很多时候都可以例外。

I tryied to envolve my action code in a try /catch but when the application thows an expcetion the npm stop working and i have to execute: 我试图将动作代码包含在try / catch中,但是当应用程序发出异常时,npm停止工作,我必须执行:

$ npm start

To get my application running back, i don't find a solution to allow the application to still running after an error. 为了使我的应用程序重新运行,我没有找到解决方案以允许该应用程序在发生错误后仍然可以运行。

i know the current error was happening because my mysql is offline but in similar cases i want to return the catch result. 我知道当前错误正在发生,因为我的mysql已脱机,但在类似情况下,我想返回捕获结果。


app.js app.js

/**
 * 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'));
});

routes/index.js 路线/index.js

/*
 * 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([]);
  }
};

Error: 错误:

/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

Fatal errors, like connection errors, are propagated to all pending callbacks. 致命错误(如连接错误)会传播到所有挂起的回调中。 This means you cannot handle such errors in try-catch blocks. 这意味着您无法在try-catch块中处理此类错误。

To handle the connection error, you'll need to call the connect method on the connection object and supply a callback to handle the error: 要处理连接错误,您需要在连接对象上调用connect方法,并提供一个回调来处理该错误:

con.connect(function (err) {
  console.log(err); // the connection error
});

You'll need to define the connection object outside the try-catch block. 您需要在try-catch块之外定义连接对象。 You'll find more information on the node-mysql documentation 您可以在node-mysql文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM