如何解决如何使用类处理快递中的错误?
我正在尝试以更好的方式处理类构造函数的错误。我将我的类命名为 HttpError 写在下面,问题是 HttpError 不能正常工作。
这是“app.js”文件:
const express = require('express');
const app = express();
const placesRoutes = require('./routes/placesRoutes');
app.use('/api/places',placesRoutes);
app.get('/',(req,res,next) => {
res.json({message: 'the server is working.'});
next();
});
app.use((error,req,next)=> {
if(res.headerSent){
return next(error);
}
res.status(error.code || 500);// This error shows when I am entering wrong pid
res.json({message: 'Does not match any route'});
})
app.listen(5000);
这是placesRoutes.js:
const express = require('express');
const HttpError = require('../models/httpError');
const router = express.Router();
const DUMMY_PLACE = [
{
id: '1',name: 'jahid',address: 'Rajoir,Rayenda,Sarankhola,Bagerhat',email: 'gahid@gmail.com',password: 'jahid5868'
},{
id: '2',name: 'saiful',{
id: '3',name: 'sadiqul',email: 'gkaid@gmail.com',{
id: '4',name: 'hasib',email: 'ahid@gmail.com',]
router.get('/:pid',next) => {
const sid = req.params.pid;
const data = DUMMY_PLACE.find(p=> p.id === sid);
if(!data){
return next(new HttpError('Does not found uid',404));
}
res.json({data});
});
module.exports = router;
这是“HttpError.js”:
class HttpError extends Error {
constructor(message,statusCode) {
super();
this.message = message;
this.statusCode = statusCode;
}
};
module.exports = HttpError;
当我输入 /api/places/:(wrong-pid) 时。它不显示 HttpError,而是显示 app.js 的 bottom 的错误 500。 我是新手,所以如果我的问题没有意义,请不要打扰。
解决方法
使用上面的代码,HttpError
的一个实例被传递给错误处理中间件,但您并没有真正在那里使用它。您可能想要执行以下操作:
app.use((error,req,res,next)=> {
if(res.headerSent){
return next(error);
}
if(error instanceof HttpError) {
res.status(error.statusCode);
res.json({message: error.message});
} else {
res.status(error.code || 500);
res.json({message: 'Does not match any route'});
}
})
,
所以基本上你有很多处理错误的方法,我喜欢使用 try/catch 块,非常简单易懂,非常有用和清晰。你正在做一个块,要求他做一些事情,如果它得到一个错误,它就会把它传递给 catch 块。
例如:
const validateUser = async (req,next) => {
try {
const { email,password } = req.body
if (!email || !password) {
throw new ErrorHandler(404,'Missing required email and password fields')
}
const user = await db.User.findOne({ where: { email }});
if (!user) {
throw new ErrorHandler(404,'User with the specified email does not exists')
}
next()
} catch (error) {
next(error)
}
}
所以我们尝试一些东西(获取数据检查它),如果有错误传递到 catch 块。
另一个最简单的例子:
try {
capture = await payPalClient.client().execute(request);
captureID = capture.result;
// console.log(captureID)
} catch (err) {
// 4. Handle any errors from the call
return res.status(500).send({
status: 500,error: err,});
}
尝试一些东西(我的一个代码中的一些贝宝东西并不重要)。 如果我从中收到错误,我会返回一个响应(500 并带有错误消息。)
您可以在 google 上查看错误处理 express try/catch
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。