nodejs,express 自制错误日志

2017-07-16 20:13:14

1.首先看Express 内置的异步错误处理

app.get('/', function (req, res) {
 throw new Error('oh no!')
})
app.use(function (err, req, res, next) {
 console.log(err.message) // 噢!不!
})

    切记把app.use  放在所有的app.use 和route后面

对于同步执行的代码,以上的处理已经足够简单。然而,当异步程序在执行时抛出异常的情况,Express 就无能为力。原因在于当你的程序开始执行回调函数时,它原来的栈信息已经丢失。


对于异步错误处理我们采用下面的方式

app.get('/', function (req, res, next) {
 queryDb(function (err, data) {
  if (err) return next(err)
  // 处理数据

  makeCsv(data, function (err, csv) {
   if (err) return next(err)
   // 处理 csv

  })
 })
})
app.use(function (err, req, res, next) {
 // 处理错误
})

    对于这种情况,可以使用 next 函数来将错误传递给下一个错误处理中间件


然后我们就可以在处理错误的地方进行日志打印  例子如下

app.use(function (err,req,res,next) {
  fs.appendFile("logs/log"+dateTime().split(' ')[0].replace(/-/g, "")+".txt",dateTime()+" "+req.originalUrl+"\n"+util.inspect(req.body)+"\n"+util.inspect(req.params)+"\n"+util.inspect(err)+"\n"+"\n",function (err) {
    if(err){
      return console.log(err)
    }
    console.log("the file was saved")
  })
  console.log(req.body)
  next()
})


  • 2017-11-01 01:30:45

    解决第三方包内jar包冲突

    这个问题就是因为引入jar包的冲突,这时我们可以在build.gradle中添加如下代码,下方单独的是添加的代码

  • 2017-11-06 01:00:17

    撤销git add

    如何撤销git add,不小心执行了git add . 操作,但是又不能提交所有的文件,因为对应不同的分支,现在怎么样可以将git add 撤销回来

  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.