欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NodeJs如何全局统一处理异常,实现RestFull风格

程序员文章站 2022-07-15 15:46:53
...

当在controller中处理客户端发来的数据时,我们会去校验数据,当数据错误时,我们会给客户端返回一个信息,如:


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, '身份证号码有误,请重填')
  }
}

但是这样子,返回给客户端的是这样的


手机号码有误,请重填

这严重不符合restFull风格,那么如何做出像Java一样的全局错误处理呢。

自定义异常类

默认的Error只能传一个string参数,我们先扩展这个Error类


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

export default BusinessError

controller中返回的不再是Error了,而是返回我们自己定义的BusinessError


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中进行拦截



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

此时返回给客户端的就是标准restFull风格的格式啦


{
    code: 100,
    msg: '手机号码有误,请重填'
}

来源:https://segmentfault.com/a/1190000016287137