在控制器中处理客户端发送的数据时,我们会对数据进行校验。当数据错误时,我们会向客户端返回一条消息,例如:exportfunctionadd(req,res,next){console.log(req.body)/*检查合法性*/try{check(req.body)}catch(error){returnnext(error)}varaddUser=newUsers(req.body)addUser.save((error,data)=>{if(error)returnnext(error)res.json(GLOBAL.SUCCESS)})functioncheck(obj){/*手机号必传且有效*/if(!(/^1[34578]\d{9}$/.test(obj.mobile))){console.log('error')thrownewError('手机号错误,请重新填写')}/*身份证合法*/if(!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(obj.idCard))){thrownewError(101,'身份证号码错误,请重新填写')}}但是这样返回给客户端的手机号是错误的,请重新填写。这严重不符合restFull的风格,那怎么让它像Java中那样进行全局错误处理呢。自定义异常类默认的Error只能传递一个字符串参数。让我们扩展这个Error类classBusinessErrorextendsError{constructor(code,msg){super(msg)this.code=codethis.msg=msgthis.name='BusinessError'}}exportdefaultBusinessErrorcontroller不再返回Error,而是返回我们自己定义的BusinessError函数检查(obj){/*手机号必传且合法*/if(!(/^1[34578]\d{9}$/.test(obj.mobile))){console.log('error')thrownewBusinessError(100,'手机号错误,请重新填写')}/*身份证合法*/if(!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(obj.idCard))){thrownewBusinessError(101,'身份证号码错误,请重新填写')}}在App.js中拦截/*抛出全局错误*/app.use((error,req,res,next)=>{if(error){res.json({msg:error.message,code:error.代码})}});此时返回给客户端的是标准的restFull格式{code:100,msg:'手机号错误,请重新填写'}
