node.js、koa2开发微信小程序后端(三)

Koa传参

  1. URL路径中传参
  2. URL问好后面传参
  3. header
  4. body
router.post('/v1/:id/classic/latest',(ctx,next)=>{
    const path = ctx.params
    const query = ctx.request.query
    const headers = ctx.request.header
//需在app.js中加入
//const parser = require('koa-bodyparser')
//app.use(parser()) //获取body参数需要的库
    const body = ctx.request.body
    console.log(path)
    console.log(query)
    console.log(headers)
    console.log(body)
    ctx.body = {
        key:'classic'
    }
})

之后可以通过postman(接口测试工具)POSTlocalhost:3000/v1/3/classic/latest后,控制台出现如下信息

{id: '3' }
[Object: null prototype] {}
{ 'comtent-type': 'application/json',
  token: '123123',
  'content-type': 'text/plain',
  'user-agent': 'PostmanRuntime/7.13.0',
  accept: '*/*',
  'cache-control': 'no-cache',
  'postman-token': 'd741d9d2-8d01-452c-bfa3-7e960592e2dc',
  host: 'localhost:3000',
  'accept-encoding': 'gzip, deflate',
  'content-length': '12',
  connection: 'keep-alive' }
{}

异常处理

  1. 没有发生异常 正确返回结果(包括返回undifind的情况)
  2. 发生了异常

函数设计异常处理方案

  1. 判断出异常 return false null
  2. throw new Error(编程规范)
//test.js
function func1(){
    try {
        func2()
    } catch (error) {
        throw error
    }
}

function func2(){
    try {
        func3()
    } catch (error) {
        throw error
    }
}
console.log(func3())
function func3(){
    try {
        console.log(0/a)
    } catch (error) {
        throw error
    }
    return 'success'
}

那么有没有一个办法可以监听到任何异常呢

异步异常处理方案

function func3(){
    setTimeout(function(){
        throw new Error('error')
    },1000)//异步执行 无法捕捉到异常
}

当连续的几个函数调用时,如果有异步处理的函数,若函数返回的是一个Peomise,那么给所有的函数加上async和await就可以实现异步异常处理。

function func1(){
    func2()
}

async function func2(){
    try {
        await func3()
    } catch (error) {
        //throw error
        console.log('error')    }
}

async function func3(){
    return new Promise((resolve,reject)=>{//对,错
        setTimeout(function(){
            const r = Math.random()
            if(r<0.5){
                reject('error')
            }
        });
    })
    /* setTimeout(function(){
        throw new Error('error')
    },1000) */
    //必须返回的是异步函数的promise包装
}
func1()

全局异常处理中间件

const Router = require('koa-router')
const router = new Router()
router.post('/v1/:id/classic/latest',(ctx,next)=>{
    const path = ctx.params
    const query = ctx.request.query
    const headers = ctx.request.header
    const body = ctx.request.body
    ctx.body = {
        key:'classic'
    }
    throw new Error('API Exception')
    //全局监听到这个错误 然后输出一段有意义的代码
})

module.exports = router

如果不处理这个错误,返回的页面为

在island目录下新建一个目录middlewares,再新建文件exception.js

//exception.js
//AOP 面向切面编程
const catchError = async(ctx,next)=>{
    try {
        await next()
    } catch (error) {
        ctx.body = '服务器有点问题,你等一下'
    }
}
module.exports = catchError
//app.js
const catchError = require('./middlewares/exception')
app.use(catchError)

定义异常处理基类

//core/http-exception.js
class HttpException extends Error{
    constructor(msg='服务器异常',errorCode=10000,code=400){//构造函数
        super()
        this.errorCode = errorCode
        this.code = code
        this.msg = msg
    }
}
class ParameterException extends HttpException{
    constructor(msg,errorCode){
        super()
        this.code = 400
        this.msg = msg || '参数错误'
        this.errorCode = errorCode || 10000
    }
}
module.exports = {
    HttpException,ParameterException
}
//middlewares/exception.js
const catchError = async(ctx,next)=>{
    try {
        await next()
    } catch (error) {
        //error 对战调用信息
        //error 简化 清晰明了的信息 给前端
        //Http Status 
        //2开头 正确
        //400参数错误 401 没有授权 403禁止访问 404nutfund 500服务器内部错误
        //error_code 比http status详细 开发者自己定义 
        //request_url 当前请求的url
        //已知错误: 用户传参不正确 明确处理
        //未知型错误 程序潜在错误 连接数据库时账号密码错误
        if(error.errorCode){
            ctx.body = {
                msg:error.msg,
                error_code:error.errorCode,
                request:`${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
        }
    }
}
module.exports = catchError  
//classic.js
const Router = require('koa-router')
const router = new Router()
//const {HttpException,ParameterException} = require('../../../core/http-exception')
router.post('/v1/:id/classic/latest',(ctx,next)=>{
    const path = ctx.params
    const query = ctx.request.query
    const headers = ctx.request.header
    const body = ctx.request.body

    if(true){
        //动态
        const error = new global.errs.ParameterException()
        //const error = new Error('为什么错误')
        //error.errorCode = 10001
        //error.status = 400
        //error.requestUrl = `${ctx.method} ${ctx.path}`
        throw error
    }
    ctx.body = {
        key:'classic'
    }

})

module.exports = router

全局异常处理

//全局变量
    static loadHttpException(){
        const errors = require('./http-exception.js')
        global.errs = errors
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值