NodeJs如何全局統一處理異常,實現RestFull風格

當在controller中處理客戶端發來的數據時,咱們會去校驗數據,當數據錯誤時,咱們會給客戶端返回一個信息,如:json

export function add (req, res, next) {
  console.log(req.body)
  /* 檢查合法性 */
  try {
    check(req.body)
  } catch (error) {
    return next(error)
  }

  var addUser = new Users(req.body)
  addUser.save((error, data) => {
    if (error) return next(error)
    res.json(GLOBAL.SUCCESS)
  })


function check (obj) {
  /* 手機號碼必傳 且合法 */
  if (!(/^1[34578]\d{9}$/.test(obj.mobile))) {
    console.log('error')
    throw new Error('手機號碼有誤,請重填')
  }

  /* 身份證合法 */
  if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(obj.idCard))) {
    throw new Error(101, '身份證號碼有誤,請重填')
  }
}

可是這樣子,返回給客戶端的是這樣的app

手機號碼有誤,請重填

這嚴重不符合restFull風格,那麼如何作出像Java同樣的全局錯誤處理呢。this

自定義異常類

默認的Error只能傳一個string參數,咱們先擴展這個Error類rest

class BusinessError extends Error {
  constructor (code, msg) {
    super(msg)
    this.code = code
    this.msg = msg
    this.name = 'BusinessError'
  }
}

export default BusinessError

controller中返回的再也不是Error了,而是返回咱們本身定義的BusinessErrorcode

function check (obj) {
  /* 手機號碼必傳 且合法 */
  if (!(/^1[34578]\d{9}$/.test(obj.mobile))) {
    console.log('error')
    throw new BusinessError(100, '手機號碼有誤,請重填')
  }

  /* 身份證合法 */
  if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(obj.idCard))) {
    throw new BusinessError(101, '身份證號碼有誤,請重填')
  }
}

在App.js中進行攔截string

/* 全局錯誤拋出 */
app.use((error, req, res, next) => {
  if (error) {
    res.json({ msg: error.message, code: error.code })
  }
});

此時返回給客戶端的就是標準restFull風格的格式啦io

{
    code: 100,
    msg: '手機號碼有誤,請重填'
}
相關文章
相關標籤/搜索