- 在core/http-exception.js中添加成功的类,并导出
class HttpException extends Error{
constructor(msg="服务器异常", errorCode=10000, code=400){
super()
this.errorCode = errorCode
this.code = code
this.msg = msg
}
}
// 参数验证提示
class ParameterException extends HttpException{
constructor(msg="参数错误", errorCode="10000"){
super()
this.code = 400
this.msg = msg
this.errorCode = errorCode
}
}
// 成功提示
class Success extends HttpException{
constructor(msg="oK", errorCode="0"){
super()
this.code = 201
this.msg = msg
this.errorCode = errorCode
}
}
module.exports = {
HttpException,
ParameterException,
Success
}
- 在user.js api文件中使用
const {Success} = require('../../../core/http-exception')
// 注册 新增
router.post('/register', async (ctx)=>{
// 思维路径
// 接收参数, validator校验
// email, password1,password2,nickname
const v = await new RegisterValidator().validate(ctx)
// 获取到传递的数据
const user = {
nickname: v.get('body.nickname'),
password: v.get('body.password1'),
email: v.get('body.email')
}
// 关联到数据库
const r = await User.create(user)
// 当注册成功
throw new Success()
})