错误处理日志

 1 const express = require('express');
 2 const fs = require('fs');
 3 const path = require('path');
 4 const app = express();
 5 
 6 app.get('/', (req, res, next)=>{
 7     try {
 8         const data = JSON.parse('{name:');//试验错误
 9         res.json(data);
10     }catch (e) {
11         //抛出错误
12         next(e);
13     }
14 });
15 
16 app.get('/b', (req, res, next)=>{
17     fs.readFile(path.join(__dirname, 'ccccc.log'), (err, data)=>{
18         if(err){
19             next(err);
20         }
21     });
22 });
23 
24 app.get('/a', (req, res, next)=>{
25     res.send('<h1>Hello World!</h1>');
26 });
27 
28 
29 /*
30   统一的错误处理日志
31 */
32 app.use((err, req, res, next)=>{
33     const error_log = `
34     =====================================
35     错误名: ${err.name}, \n
36     错误信息:${err.message}, \n
37     错误时间:${new Date()}, \n
38     错误堆栈:${err.stack}, \n
39     =====================================
40     `;
41     fs.appendFile(path.join(__dirname, 'error.log'), error_log, (err)=>{
42         res.writeHead(500, {'Content-Type': 'text/html;charset=utf-8'});
43         res.end('500 服务器内部错误!')
44     });
45 });
46 
47 app.use((req, res, next)=>{
48     res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'});
49     res.end('404 您访问的资源不存在!')
50 });
51 
52 app.listen(3000, ()=>{
53    console.log('running.....')
54 });

 

posted @ 2019-07-07 15:16  疏影横斜水清浅  阅读(212)  评论(0编辑  收藏  举报