我正在用Reactjs前端和Node.js后端api制作一个应用程序,在某个地方我遇到类似这样的错误。
但是在这里,我只想得到此消息email: {message: "This email is already taken",
,我尝试使用一些在线工具来解析此错误,但是当我尝试使用它们时,我从后端得到了错误。
这是使用errorparser后的错误
(node:14208) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
at exports.default (C:/projects/bookworm-practice/bookworm-api/src/utils/parseErrors.js:5:15)
at C:/projects/bookworm-practice/bookworm-api/src/routes/users.js:14:54
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14208) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14208) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
这是我的parseError函数
import _ from 'lodash';
export default function () {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}
这是我使用parseError的用户功能
import express from 'express';
import User from '../models/User';
import parseErrors from '../utils/parseErrors';
const router = express.Router();
router.post('/', (req, res) => {
const { email, password } = req.body.user;
const user = new User({ email });
user.setPassword(password);
user.save()
.then(user => res.json({ user: user.toAuthJSON() }))
//.catch(err => res.json({ err })); // this is the default one
.catch(err => res.status(400).json({ errors: parseErrors(err.errors)
//this is after adding parseErrors funtion
}))
})
export default router;
答案 0 :(得分:1)
您的parseErrors函数不包含错误作为参数
import _ from 'lodash';
export default function (errors) {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}