要点

主要是app.use的callback中参数不同产生的多态,有err参数会处理错误,没有的会处理其他

code

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