zoukankan      html  css  js  c++  java
  • koa-json-error处理错误中间件

    koa 错误处理中间件 koa-json-error

    在写接口时,返回json格式且易读的错误提示是有必要的,koa-json-error中间件帮我们做到了

    安装使用koa-json-error

    npm i koa-json-error -S
    const error = require('koa-json-error')`
    app.use(error({
        postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
    }))

    错误会默认抛出堆栈信息,在生产环境中,没必要返回给用户,在开发环境显示即可

    412错误 先决条件出错

    // code 
    ctx.throw(412, '先决条件失败:id大于数据长度')

    返回错误信息

    {
        "message":"先决条件失败:id大于数据长度",
        "name":"PreconditionFailedError",
        "status":412
    }
    500 错误
    模拟出错代码
    
    a.b
    复制代码
    {
        "name": "ReferenceError",
        "message": "a is not defined",
        "status": 500
    }
    404错误
    请求无响应的url
    堆栈示例
    {
        "stack":"NotFoundError: Not Found
            at Object.throw (/Users/zj/code/koa-restful/node_modules/koa/lib/context.js:97:11)
            at next.then (/Users/zj/code/koa-restful/node_modules/koa-json-error/lib/middleware.js:52:58)
            at process._tickCallback (internal/process/next_tick.js:68:7)",
        "message":"Not Found",
        "name":"NotFoundError",
        "status":404
    }
  • 相关阅读:
    解决Cannot delete or update a parent row: a foreign key constraint fails的mysql报错
    zabbix4.2绘制网络拓扑图-添加链路速率
    zabbix 添加宏变量
    238_Product of Array Except Self
    122_Best Time to Buy and Sell Stock II
    260_Single Number III
    C# 比较时间问题
    226_Invert Binary Tree
    100_Same Tree
    283_Move Zeroes
  • 原文地址:https://www.cnblogs.com/webljl/p/14014864.html
Copyright © 2011-2022 走看看