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-02-10 16:22:13

    git历史记录查询

    查看提交历史:git log 查看提交历史并显示版本间的差异:git log -p 查看指定历史:git log xxx(sha1值) -p 查看提交历史(指定时间):

  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).

  • 2017-02-16 08:09:01

    HTML中PRE和p的区别

    pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 <pre> 标签的一个常见应用就是用来表示计算机的源代码。

  • 2017-02-16 15:14:14

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。