Created
October 9, 2015 03:29
-
-
Save Gaubee/add5ecc7e807578e181d to your computer and use it in GitHub Desktop.
测试Express的错误处理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 创建类似DB服务 | |
*/ | |
var net = require("net"); | |
var server = net.createServer(function(c) { | |
console.log('DB-SERVER: client connected'); | |
c.on('end', function() { | |
console.log('DB-SERVER: client disconnected'); | |
}); | |
c.on('data', function(chunk) { | |
chunk.toString().split("\n").forEach(time => { | |
var _tcp_req_id = time.split("|")[0]; | |
var time = +time.substr(_tcp_req_id.length + 1); | |
if (!time) { | |
return | |
} | |
setTimeout(function() { | |
c.write(_tcp_req_id + "kill " + time); | |
}, time) | |
}); | |
}); | |
}); | |
server.listen(8125, function() { | |
console.log('TCP SERVER START!'); | |
}); | |
/* | |
* 与DB服务初始化连接,单例模式 | |
*/ | |
var client = net.connect({ | |
port: 8125 | |
}, function() { //'connect' listener | |
console.log('DB-client: connected to server!'); | |
/* | |
* 初始化WEB服务 | |
*/ | |
var express = require("express"); | |
var app = express(); | |
app.get('/', function(req, res, next) { | |
//根据传进来的时间参数来设定抛出错误的时间 | |
console.log(req.query) | |
var _tcp_req_id = Math.random(); | |
client.write(_tcp_req_id + "|" + req.query.t + "\n"); | |
client.once('data', function _cb(chunk) { | |
chunk = chunk.toString().split(_tcp_req_id); | |
if (chunk.length <= 1) { | |
client.once("data", _cb); //重新注册事件 | |
return | |
} | |
chunk = chunk[1]; | |
//直接抛出,client是不守express-app所管制,所以express-app是捕捉不到这个错误的 | |
var err = new Error(chunk); | |
if (req.query.use_next) { | |
next(err); | |
} else { | |
throw err | |
} | |
}); | |
}); | |
var server = app.listen(2333, function() { | |
var host = server.address().address; | |
var port = server.address().port; | |
console.log('Example app listening at http://%s:%s', host, port); | |
}); | |
//Error handling | |
app.use(function(err, req, res, next) { | |
console.error(err.stack); | |
res.status(500).send('Something broke!'); | |
}); | |
/* | |
* 请求web服务 | |
*/ | |
var http = require("http"); | |
http.get("http://localhost:2333?t=2000&use_next=true"); | |
http.get("http://localhost:2333?t=1000&use_next=true"); | |
http.get("http://localhost:2333?t=4000"); | |
http.get("http://localhost:2333?t=3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment