通过.catch

时间:2016-12-20 18:37:12

标签: javascript node.js express exception q

我正在使用Express和q promise库构建应用程序(Winston用于日志记录,restler用于http请求)。

我想要完成的是:当代码抛出异步错误并由catch子句捕获时,我希望快速错误处理程序处理该错误。

我编写了代码,但是当我浏览上面提到的场景时,应用程序会挂断。您将在self.index中看到catch子句。

更新:我已根据idbehold建议更新了self.index。还没有工作。

任何帮助将不胜感激。提前谢谢。

index.controller.js

"use strict"

let Q = require("q"),
    restConnector = require("restler"),
    winston = require("winston"),
    logger = new winston.Logger({
        level: 'info',
        transports: [
            new winston.transports.Console(),
            new winston.transports.File({ filename: 'log.log' })
        ],
        exitOnError : false
    }),
    self = {};

self.get = function(url, options) {
    let deferred = Q.defer();
    let opts = (options||{})
    opts.timeout = opts.timeout || 500

    logger.info("url: " + url);



    restConnector.get(url, opts)

        .on('success', (response) => {
            deferred.resolve(response);
        })
        .on('fail', (err) => {logger.info("fail"); deferred.reject(err)})
        .on('error', (err) => {logger.info("error"); deferred.reject(err)})
        .on('timeout', (err) => {logger.info("timeout"); deferred.reject(err)});

    return deferred.promise;
};

//UPDATE: idbehold
self.index =  (req, res, next) => {

    logger.info("Logging info");

    return self.get("http://api2-ci.example.com/post/5854346").then( (cart) => {
            logger.log("info", "log", cart);
            res.render('index', { title: 'Express from Controller' });
        }).catch(next);

}

module.exports = self;

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');

  next(err);
});

module.exports = app;

index.js(路线)

let express = require('express');
let router = express.Router();
let indexCtrl = require('../controllers/index.controller');

router.get('/', indexCtrl.index);

module.exports = router;

1 个答案:

答案 0 :(得分:0)

更改index.controller.js中的路由定义

self.index = (req, res, next) => {
    logger.info("Logging info");
    return self.get("http://api2-ci.example.com/post/5854346").then( (cart) => {
        logger.log("info", "log", cart);
        res.render('index', { title: 'Express from Controller' });
    }).catch(next);
};