错误处理


使用 try catch 来处理错误

const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
  try {
    JSON.parse('abc')
    ctx.body = 'Hello Koa'
  } catch (error) {
    ctx.response.status = 500 // 设置状态码
    ctx.body = '服务器内部错误'
  }
})

app.listen(4001)
  • 使用 try catch 手动处理错误

使用上下文中的 throw 方法处理错误

const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
  try {
    JSON.parse('abc')
    ctx.body = 'Hello Koa'
  } catch (error) {
    ctx.throw(500) // 状态码500 并且会响应 Internal Server Error
  }
})

app.listen(4001)
  • 使用 ctx.throw 方法快速设置状态码

利用洋葱圈模型统一处理错误

const Koa = require('koa')
const app = new Koa()

app.use(async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    ctx.status = 500
    ctx.body = '服务端内部错误'
  }
})

app.use(ctx => {
  JSON.parse(abc)
  ctx.body = 'hello koa'
})

app.listen(4001)
  • 后续所有中间件执行过程中发生异常都会通过洋葱圈模型中的第一个中间件来处理

监听实现错误处理

const Koa = require('koa')
const fs = require('fs')
const { promisify } = require('util')
const readFile = promisify(fs.readFile)
const app = new Koa()

app.use( (ctx, next) => {
  console.log(1)
   next()
})

app.use(async ctx => {
  const data = await readFile('****')
  ctx.type = 'html'
  ctx.body = data
})

app.on('error', error => {
  console.log(error)

})

app.listen(4001)
koa