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

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

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

课程讲师: 7七月

课程内容:

参数获取与 LinValidator 效验器

npm install koa-bodyparser
const parser = require('koa-bodyparser') // 解析body
app.use(parser())

使用

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
})

异常理论与异常链

在根目录新建 middlewares 文件夹中新建一个 exception.js 文件
全局异常处理

const catchError = async (ctx, next) => {
	try{
		await next()
    } catch(error) {
	    // 全局异常错误提示
	    ctx.body = '服务器有点慢'
    }
}
module.exports = catchError

// 导入到 app.js 文件进行注册成为一个中间件
const catchError = require('catchError')
app.use(catchError)

已知错误与未知错误

已知错误: 客户端传递的参数错误之类的
未知错误: 连接数据库 账号或者密码错误, 后端代码写错了之类的

定义 HttpException 异常基类

在 core 文件夹中创建 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
}

// 外部调用
// 引入
// 使用
const error = new HttpException('为什么错误', '10001', 400)
throw error // 为什么要继承 Error 类 因为要使用 throw 抛出错误

因为抛出的是一个已知错误是一个 Httpexception 类, 可以用这个来判断是否是已知错误

const HttpException = require('HttpException')
const catchError = async (ctx, next) => {
	try{
		await next()
    } catch(error) {
	    // 全局异常错误提示
		// 已知错误
		if(error instanceof HttpException) {
			// 判断是否是 HttpException 这个类创建的实例对象
			ctx.body = {
				msg: error.msg,
				errorCode: error.errorCode,
				request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
        }
    }
}
module.exports = catchError

特定异常类与 global 全局变量

上面那个异常基类在使用的时候并不是很方便, 每次使用都需要导入, 可以使用全局的方法在 global 中进行挂载
也可以定义一些具体的异常让他们去 继承 基类
http-exception.js

class ParameterException extends HttpException {
	constructor(msg, errCode){
		super()
		this.code = 400
		this.msg = msg || '参数错误'
		this.errorCode = errorCode || 10000
    }
}
module.exports = {
HttpException,
ParameterException
}

每次都要导入太麻烦啦 , 用global 进行挂载
在 core/init.js 文件中, 创建一个静态方法

static loadHttpException () {
	const errors = require('http-exception') // 获取到全部的异常类
	global.errs = errors
}

// 在 initCore 入口方法进行初始化 每当应用程序启动都会去执行
InitManager.loadHttpException()

// 外部访问
throw new global.errs.ParameterException()

课程收获

通过这章学习, 学习了项目的工程化, 异常错误的处理

课程截图

图片描述

上节课程作业

课题

class A {
    constructor() {
        this.nameA = 'a'
    }
    validateA() {
        console.log("A")
    }
}

class B extends A {
    constructor() {
        super()
        this.nameB = 'b'
    }

    validateB() {
        console.log("B")
    }
}

class C extends B {
    constructor() {
        super()
        this.nameC = 'c'
    }

    validateC() {
        console.log("C")
    }
}
// 编写一个函数 findMembers 拿到所有的属性名和方法名
// 只能 原型链 进行查找 

答案

const c = new C()
const arr = findMembers(c, 'name', 'validate')
console.log(arr) // [ 'nameA', 'nameB', 'nameC', 'validateC', 'validateB', 'validateA' ]

function findMembers(type, name, validate) {

  function _find(type) {
    if (type.__proto__ === null) { // 找到最后了
      return []
    }
    let names = Reflect.ownKeys(type) // 拿到这个类的所有属性 返回一个数组
    names = names.filter(item => {
      // 过滤掉不满足条件的属性或方法名
      return filterItem(item)
    })
    // 结构到数组中
    return [...names, ..._find(type.__proto__)]
  }

  function filterItem(item) {
    // 如果都包含了指定的属性和方法名
    if (item.startsWith(name) || item.startsWith(validate)) {
      return item
    }
  }

  return _find(type)
}

点击查看更多内容
TA 点赞

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

评论

作者其他优质文章

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

100积分直接送

付费专栏免费学

大额优惠券免费领

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

举报

0/150
提交
取消