生活随笔
收集整理的這篇文章主要介紹了
koa --- 使用中间件多层级抛出错误
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
說明
- 能夠熟練的掌握錯誤的拋出,可以在一定程度上提高代碼的開發(fā)效率和可讀性
構(gòu)造錯誤
- 本栗采用調(diào)用一個不存在的函數(shù)來拋出錯誤
const Koa
= require('koa');
const app
= new Koa();
app
.use(async (ctx
, next
) => {await next();const rt
= ctx
.response
.get('X-Response-Time');console
.log(`輸出倒計時: ${ctx.method} ${ctx.url} - ${rt}`);
});
app
.use(async (ctx
, next
) => {const start
= Date
.now();console
.log('開始計時');await next();const ms
= Date
.now() - start
;ctx
.set('X-Response-Time', `${ms}ms`);console
.log('結(jié)束計時');
})
app
.use(async ctx
=>{await sleep(250);ctx
.status
= 200;ctx
.type
= 'html';ctx
.body
= `
<h1
>Hello Koa
</h1
>
})
根據(jù)洋蔥模型: 首先執(zhí)行 const start = Date.now()console.log('開始計時');遇到await next()跳到下一個中間件,并將await next()后面的代碼入一個函數(shù)調(diào)用棧執(zhí)行await sleep(250)由于sleep函數(shù)未定義,于是拋出錯誤
const rt = ctx.response.get('X-Response-Time'): 獲取請求頭部中’X-Response-Time’的值ctx.set('X-Response-Time', '${ms}ms'): 返回頭部’X-Response-Time’添加值
koa級別拋出錯誤,并獲取處理錯誤
- 拋出錯誤不進(jìn)行處理
- 將該中間件放在倒數(shù)第二個中間件的位置.
app
.use(async (ctx
, next
) => {try {await next();} catch (error) {ctx
.status
= error
.statusCode
|| error
.status
|| 500;ctx
.body
= error
.message
;ctx
.app
.emit('error', error
, ctx
);console
.log("中間件捕捉:", error
.message
);}
})
try{ await next() }: 嘗試運行下一個中間件,如果遇到錯誤則運行catch塊中的代碼ctx.body = error.message: 用戶級別的拋出錯誤,用于再瀏覽器中提醒用戶錯誤的信息ctx.app.emit('error', error, ctx): koa框架應(yīng)用層級的錯誤,錯誤的標(biāo)識為’error’,可以通過app.on('error')來進(jìn)行處理.由于此處沒有app.on('error'),因此會默認(rèn)的執(zhí)行以下語句
app
.on('error', err
=>{console
.error(err
);
})
- 使用app.on('error', err=>{}) 處理
app
.on('error', err
=>{throw err
;
})
總結(jié)
以上是生活随笔為你收集整理的koa --- 使用中间件多层级抛出错误的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。