NodeJS 表示不执行错误处理中间件

6jjcrrmo  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(177)

这是服务器:

app.use(authMiddleware)
app.use(express.json())
app.use(CUSTOMERS, customerRouter)
app.use(handleError)
function startServer() {

所以handle error是最后一个中间件,这是路由代码:
创建用户的路由具有如下验证:

const userRouter: Router = Router()
userRouter.post('/', validateUser, newUser)

新用户功能如下:

async function newUser(
  request: Request,
  response: Response,
  next: NextFunction
) {
  try {
    const user = await createUser(request.body)
    return response.status(201).json(user)
  } catch (err) {
    console.log('why not!', err)//I can see this log
    return next(err)
  }
}


当验证程序检测到无效post时,它将工作并调用错误处理程序:

function validateUser(
  request: Request,
  response: Response,
  next: NextFunction
) {
  const errors = validate(request.body)
  errors.length
    ? next(new HttpError(400, 'Invalid user sent', errors))
    : next()
  next()
}

但当我发送有效的用户主体,但它包含一个已在使用的电子邮件,createUser将抛出,它被newUser捕获(日志显示),但错误处理程序从未被调用。

function handleError(
  error: HttpError,
  req: Request,
  response: Response,
  _next: NextFunction//yes, added next, express is using length for some reason
) {
  console.log('returning json', error)//never see this log on duplicate email
  return response.status(error.status ?? 500).json({
    message: error.message,
    errors: error.errors,
  })
}
l0oc07j2

l0oc07j21#

在validateUser中,我将调用以下两次:

const errors = validate(request.body)
  errors.length
    ? next(new HttpError(400, 'Invalid user sent', errors))
    : next()
  next()//do not need this one

删除那个解决了问题,但为了更好地衡量,我删除了newUser中的返回:

async function newUser(
  request: Request,
  response: Response,
  next: NextFunction
) {
  try {
    const user = await createUser(request.body)
    return response.status(201).json(user)
  } catch (err) {
    console.log('why not!', err)//I can see this log
    //return next(err)
    next(err)
  }
}

相关问题