为了账号安全,请及时绑定邮箱和手机立即绑定

【金秋打卡】第15天 《Node.js+Koa2+MySQL 打造前后端分离精品项目》

课程名称:Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》

课程章节:第4章【深入浅出讲异常】异步异常与全局异常处理

视频:4-6 定义异常返回格式
            4-7 定义HttpException异常基类

课程讲师: 七月

课程内容:

这节课规范了出现异常后的返回格式,返回数据中包含了msg,code status url等常见属性

//改动后的代码
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

    // true 仅仅为了测试
    if (true) {
        const error = new Error("出现了错误")
        error.errorCode = 10001
        error.status = 400
        error.requestUrl = `${ctx.method} ${ctx.path}`
        throw error
    }
    ctx.body = {
        key: 'classic',
        path: path,
        query,
        headers,
        body
    }

    //throw new Error('API Exception')
})


module.exports = router
//改动后的代码
const catchErrof = async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        if (error.errorCode) {
            ctx.body = {
                msg: error.message,
                error_code: error.errorCode,
                request: error.requestUrl,
               
            }
            ctx.status = error.status
        }
    }
}
module.exports = catchErrof

post访问 http://localhost:3000/v1/4/classic/latest?param=apple 后,可以得到如下格式的返回

{
    "msg": "出现了错误",
    "error_code": 10001,
    "request": "POST /v1/4/classic/latest"
}

4-7 定义HttpException异常基类

上节课的写法很麻烦,可以定义一个类,继承Error 把自己的信息封装到类中。

继承的类中写一个初始的方法,constructor,并接受三个参数,msg、errorCode、code。

封装为HttpException的好处目前看起来不明显,后续章节会详细讲解这样设计的好处。

//重构的exception.js
const { HttpException } = require("../core/http-exception")

const catchErrof = async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        if (error instanceof HttpException) {
            ctx.body = {
                msg: error.msg,
                error_code: error.errorCode,
                request: `${ctx.method} ${ctx.path}`,
               
            }
            ctx.status = error.code
        }
    }
}
module.exports = catchErrof
//新建立的http-exception.js
class HttpException extends Error{
    constructor(msg='服务器异常', errorCode=10000, code=400) {
        super()
        this.errorCode = errorCode
        this.code = code
        this.msg = msg
    }
}

module.exports = {
    HttpException
}
//重构的classic.js
const Router = require('koa-router')
const router = new Router()
const { HttpException } = 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

    // true 仅仅为了测试
    if (true) {
        const error = new HttpException("出现了错误2", 10001, 400)
        throw error
    }
    ctx.body = {
        key: 'classic',
        path: path,
        query,
        headers,
        body
    }

    //throw new Error('API Exception')
})


module.exports = router


课程收获:

这节课规范了规范了异常的返回格式,之后又新建了HttpException类,继承Error类。在HttpException类中写了方法,项目变得也来越整洁,项目结构变得越来越好。


七月老师非常注重在讲编程知识的同时,讲编程思维,讲知识和知识之间的关系。编程是实践性非常强的工作,学习知识最好的方法是放到项目中。做项目的目的不是做项目,最终要做出来自己的项目,业务承载的是编程知识。明天继续刷后边的课程。


https://img1.sycdn.imooc.com//636906c90001a0be11320641.jpg

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消