设置:nodejs,express, mongodb,mongoose 相关代码: var express = require('express');var server = express();server.use(express.bodyParser());server.use(express.methodOverride());server.use(server.router);var mongoose = require('mongoo
相关代码:
var express = require('express'); var server = express(); server.use(express.bodyParser()); server.use(express.methodOverride()); server.use(server.router); var mongoose = require('mongoose'); mongoose.connect('localhost', 'test'); var Schema = mongoose.Schema; var VehicleSchema = new Schema({ name : String }, {collection: 'vehicles'}); var Vehicle = mongoose.model('vehicle', VehicleSchema); server.use(clientErrorHandler); function clientErrorHandler(err, req, res, next) { console.log('client error handler found', err); res.send(500, err); } server.get('/api/test', function(req, res, next){ Vehicle.find().exec(function(err, rows){ res.send(rows); }); }); server.listen(1981);
这将按预期返回一个空数组.
在这里抛出异常:
server.get('/api/test', function(req, res, next){ throw 'my exception';// <------------------------ here Vehicle.find().exec(function(err, rows){ res.send(rows); }); });
正如预期的那样,clientErrorHandler捕获异常.相反,扔在这里:
server.get('/api/test', function(req, res, next){ Vehicle.find().exec(function(err, rows){ throw 'my exception';// <------------------------ here res.send(rows); }); });
然后,clientErrorHandler不捕获该异常,而是由mongoose / lib / util.js捕获并重新抛出该异常.
exports.tick = function tick (callback) { if ('function' !== typeof callback) return; return function () { try { callback.apply(this, arguments); } catch (err) { // only nextTick on err to get out of // the event loop and avoid state corruption. process.nextTick(function () { throw err; //<--------------------------------- here }); } } }
做一些没有猫鼬的事情,例如:
server.get('/api/test', function(req, res, next){ process.nextTick(function(){ throw 'here'; }); });
也没有被快递抓住.
我如何避免它被猫鼬而不是表达?我怎样才能表达以发现错误?我可以获得快递以捕获单独的勾号上的错误吗? (这是我要报告的内容吗?)
我想避免process.error,因为我希望能够将消息发送回该用户.我意识到可以用错误调用’next’,我更关心来自其他库的其他异常.
您应该在下一个回调时返回错误,然后由应用程序的错误处理程序处理,而不是抛出异常.如果您正在调用可能抛出自己错误的函数,请将它们包装在try子句中,并使用catch中捕获的错误调用回调.这是一个例子:
server.get('/api/test', function (req, res, next) { process.nextTick(function () { try { functionWhichWillThrowAnError(); } catch (error) { next(error); return; } res.send('everything is okay!'); }); });