node項目中的錯誤處理
node中Error對象的使用
使用captureStackTrace方法加入自帶的錯誤信息
// Error對象自帶的屬性Error.captureStackTrace// 如何使用captureStackTracevar obj = { message: 'something is wrong'}Error.captureStackTrace(obj)throw obj // 此時會拋出obj對象的message內(nèi)信息使用try catch捕獲錯誤
直接把代碼寫在try catch中即可捕獲錯誤信息
try{ throw new Error('oh no')}catch(e){ console.log(e)}在異步代碼中,直接try catch是無法捕獲錯誤信息的,可以使用如下方法
function foo(params, cb){ const error = new Error('something is wrong') if(error) cb(error)}以上使用callback方式來做錯誤處理比較容易麻煩,容易出錯,現(xiàn)在node已經(jīng)支持async await所以盡量使用它們準(zhǔn)沒錯
async function foo(){ try{ await bar() }catch(e){ console.log(e) }}async function bar(){ throw new Error('async function got wrong)}foo()基本錯誤類型
在項目會有多個地方對錯誤信息進(jìn)行處理,所以先寫一個基本錯誤類型,方便使用
// 基本錯誤類型class HttpBaseError extends Error { constructor(httpStatusCode, httpMsg, errCode, msg) { super(`HTTP ERROR: ${msg}`); this.httpStatusCode = httpStatusCode; this.httpMsg = httpMsg; this.errCode = errCode; }}try {// 直接拋出定義好的錯誤即可 throw new HttpBaseError(404, '資源不存在', 10000, 'resouse is not found');} catch (e) { console.log(e.message); console.log(e.httpStatusCode); console.log(e.httpMsg); console.log(e.errCode);}特定錯誤類型
除了基本類型,不同情況下會有不同錯誤信息,需要用一個特定的錯誤類型來處理特定的錯誤信息
// 一個參數(shù)錯誤類型const ERROR_CODE = 40000 // 錯誤碼class HttpRequestParamError extends HttpBaseError { constructor(paramName, desc, msg) { super(200, desc, ERROR_CODE, `${paramName} wrong: ${msg}`) }}這樣,在參數(shù)錯誤的地方就能非常方便的調(diào)用這個錯誤類型來返回錯誤
拋錯的邏輯
錯誤處理中,model,controller中的錯誤,有些是不能直接返回給用戶的,應(yīng)該只返回給model或controller的調(diào)用者。
使用錯誤處理
正常接口,controller,model的錯誤,使用設(shè)定好的錯誤類型進(jìn)行處理,例如前面寫的HttpRequestParamError,在所有所有路由的最后,需要使用一個error handler來對所有的錯誤進(jìn)行集中處理
// error handlerfunction handler(options) { return function (err, req, res, next) { if (err instanceof HttpRequestParamError) { // 這里對不同的錯誤做不同的處理 console.log('http request error') res.statusCode = err.httpStatusCode res.json({ code: err.errCode, msg: err.httpMsg }) } else { // 設(shè)定之外的錯誤,把管理權(quán)向外移交 next(err) } }}
新聞熱點
疑難解答
圖片精選