简介

用来将错误日志记录在数据库中以及响应前端错误信息和状态码的中间件

代码

  1. 先连接mongo数据库以及创建集合

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    const mongoose = require('mongoose')

    mongoose.connect('mongodb://localhost:27017/edu', { useNewUrlParser: true, useUnifiedTopology: true })

    let Schema = mongoose.Schema
    let errorSchema = new Schema({
    errName: {
    type: String,
    require: true
    },
    errMessage: {
    type: String,
    require: true
    },
    errStack: {
    type: String,
    require: true
    },
    errTime: {
    type: Date,
    require: true
    }
    })

    const ErrData = mongoose.model('ErrData', errorSchema)
  2. 处理错误日志以及导出该模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    module.exports = (errlog,req,res,next)=> {
    new ErrData({
    errName: errlog.name,
    errMessage: errlog.message,
    errStack: errlog.stack,
    errTime: new Date()
    }).save((err,result) =>{
    res.status(500).json({
    err_code: 500,
    err_message: errlog.message
    })
    })
    }
  3. app.js导入该模块并调用,注意各个中间件的先后顺序

    1
    2
    var errorLog = require('./middlewave/errpr-log') 
    app.use(errorLog)