这是服务器:
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,
})
}
1条答案
按热度按时间l0oc07j21#
在validateUser中,我将调用以下两次:
删除那个解决了问题,但为了更好地衡量,我删除了newUser中的返回: