Authored by ccbikai

add error handler

@@ -7,7 +7,6 @@ @@ -7,7 +7,6 @@
7 7
8 const config = require('./config/common'); 8 const config = require('./config/common');
9 9
10 -  
11 // use one apm 10 // use one apm
12 if (config.useOneapm) { 11 if (config.useOneapm) {
13 require('oneapm'); 12 require('oneapm');
@@ -20,16 +19,12 @@ const cookieParser = require('cookie-parser'); @@ -20,16 +19,12 @@ const cookieParser = require('cookie-parser');
20 const favicon = require('serve-favicon'); 19 const favicon = require('serve-favicon');
21 const session = require('express-session'); 20 const session = require('express-session');
22 const memcached = require('connect-memcached'); 21 const memcached = require('connect-memcached');
23 -const _ = require('lodash'); 22 +const hbs = require('express-handlebars');
24 const pkg = require('./package.json'); 23 const pkg = require('./package.json');
25 -const cookie = require('./library/cookie');  
26 24
27 const app = express(); 25 const app = express();
28 const MemcachedStore = memcached(session); 26 const MemcachedStore = memcached(session);
29 27
30 -const setChannel = require('./doraemon/middleware/set-channel');  
31 -  
32 -  
33 // 向模板注入变量 28 // 向模板注入变量
34 app.locals.devEnv = app.get('env') === 'development'; 29 app.locals.devEnv = app.get('env') === 'development';
35 app.locals.version = pkg.version; 30 app.locals.version = pkg.version;
@@ -37,8 +32,15 @@ app.locals.version = pkg.version; @@ -37,8 +32,15 @@ app.locals.version = pkg.version;
37 // 指定libray目录 32 // 指定libray目录
38 global.library = path.resolve('./library/'); 33 global.library = path.resolve('./library/');
39 34
40 -  
41 app.set('view engine', '.hbs'); 35 app.set('view engine', '.hbs');
  36 +app.set('views', './doraemon/views');
  37 +app.engine('.hbs', hbs({
  38 + extname: '.hbs',
  39 + defaultLayout: 'layout',
  40 + layoutsDir: './doraemon/views',
  41 + partialsDir: './doraemon/views/partial',
  42 + helpers: require(`${global.library}/helpers`)
  43 +}));
42 44
43 app.use(favicon(path.join(__dirname, '/public/favicon.ico'))); 45 app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
44 app.use(express.static(path.join(__dirname, 'public'))); 46 app.use(express.static(path.join(__dirname, 'public')));
@@ -65,35 +67,35 @@ app.use(session({ @@ -65,35 +67,35 @@ app.use(session({
65 }) 67 })
66 })); 68 }));
67 69
68 -  
69 -// req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等  
70 app.use((req, res, next) => { 70 app.use((req, res, next) => {
71 - req.yoho = {};  
72 - res.yoho = {};  
73 - next();  
74 -}); 71 + req.user = {}; // 全局的用户数据
  72 + req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等
75 73
76 -app.use((req, res, next) => {  
77 - req.user = {};  
78 -  
79 - // 从 PHP 写的 SESSION 中获取到当前登录用户的 UID  
80 - if (req.session && _.isNumber(req.session._LOGIN_UID)) {  
81 - req.user.uid = req.session._LOGIN_UID;  
82 - }  
83 -  
84 - // session 没有读取到的时候,从 cookie 读取 UID  
85 - if (!req.user.uid && req.cookies._UID) {  
86 - req.user.uid = cookie.getUid(req);  
87 - }  
88 next(); 74 next();
89 }); 75 });
90 76
  77 +const logger = require('./library/logger');
  78 +const user = require('./doraemon/middleware/user');
  79 +const setChannel = require('./doraemon/middleware/set-channel');
  80 +const errorHanlder = require('./doraemon/middleware/error-hanlder');
  81 +
  82 +// YOHO 前置中间件
  83 +app.use(user());
91 app.use(setChannel()); 84 app.use(setChannel());
92 85
93 // dispatcher 86 // dispatcher
94 -require('./dispatch')(app); 87 +try {
  88 + require('./dispatch')(app);
  89 +
  90 + app.all('*', errorHanlder.notFound()); // 404
  91 +
  92 + // YOHO 后置中间件
  93 + app.use(errorHanlder.serverError());
  94 +} catch (err) {
  95 + logger.error(err);
  96 +}
95 97
96 // listener 98 // listener
97 app.listen(config.port, function() { 99 app.listen(config.port, function() {
98 - console.log('yohobuy start'); 100 + logger.info('yohobuy start');
99 }); 101 });
  1 +/**
  2 + * 404 错误
  3 + * @return {[type]}
  4 + */
  5 +exports.notFound = () => {
  6 + return (req, res) => {
  7 + if (req.xhr) {
  8 + return res.status(404).json({
  9 + code: 404,
  10 + message: '页面不存在'
  11 + });
  12 + }
  13 + return res.render('error/404');
  14 + };
  15 +};
  16 +
  17 +/**
  18 + * 服务器错误
  19 + * @return {[type]}
  20 + */
  21 +exports.serverError = () => {
  22 + return (err, req, res, next) => {
  23 + if (!res.headersSent) {
  24 + if (req.xhr) {
  25 + return res.status(500).json({
  26 + code: 500,
  27 + message: '服务器错误'
  28 + });
  29 + }
  30 +
  31 + return res.render('error/500', err);
  32 + }
  33 + next(err);
  34 + };
  35 +};
@@ -19,7 +19,6 @@ module.exports = () => { @@ -19,7 +19,6 @@ module.exports = () => {
19 }); 19 });
20 20
21 req.yoho.channel = channel; 21 req.yoho.channel = channel;
22 - res.yoho.channel = channel;  
23 } 22 }
24 23
25 next(); 24 next();
  1 +const _ = require('lodash');
  2 +const cookie = require('../../library/cookie');
  3 +
  4 +module.exports = () => {
  5 + return (req, res, next) => {
  6 + // 从 SESSION 中获取到当前登录用户的 UID
  7 + if (req.session && _.isNumber(req.session._LOGIN_UID)) {
  8 + req.user.uid = req.session._LOGIN_UID;
  9 + }
  10 +
  11 + // session 没有读取到的时候,从 cookie 读取 UID
  12 + if (!req.user.uid && req.cookies._UID) {
  13 + req.user.uid = cookie.getUid(req);
  14 + }
  15 +
  16 + next();
  17 + };
  18 +};