【金秋打卡】第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 = catchErrofpost访问 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类中写了方法,项目变得也来越整洁,项目结构变得越来越好。
七月老师非常注重在讲编程知识的同时,讲编程思维,讲知识和知识之间的关系。编程是实践性非常强的工作,学习知识最好的方法是放到项目中。做项目的目的不是做项目,最终要做出来自己的项目,业务承载的是编程知识。明天继续刷后边的课程。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
