提问人:Eraserhead_18 提问时间:7/2/2023 更新时间:7/2/2023 访问量:55
getContact API 调用将持续运行,不会引发错误。解决方法是什么?
The getContact api call keeps running and does not throw an error. What is the fix?
问:
//@desc Get contact
//@route GET api/contacts/:id
//@access public
const getContact = asyncHandler(async (req,res) => {
const ret = await Contact.findById(req.params.id)
console.log(ret); // Line 6
if(!(await ret)){
res.status(404);
throw new Error("Contact not found");
}
res.status(200).json(ret);
});
上面的代码是 api 调用,我尝试检索通过参数传递的 ID 为“id”的联系人。
errorHandler:
// In this componenet, all errors of this application will be dealt with.
//Import constants for cleaner error handling
const constants = require("../constants");
// Errors consist of error, response, request and the next function
const errorHandler = (err, req, res, next) =>{
// When an error is caused, we check the status of the response and determine the cause
const status = res.statusCode? res.statusCode : 500;
switch(status){
case 400:
res.json({
title: "BAD REQUEST",
message: err.message,
stackTrace: err.stack
});
break;
case 404:
res.json({
title: "NOT FOUND",
message: err.message,
stackTrace: err.stackTrace
});
break;
case 403:
res.json({
title: "FORBIDDEN REQUEST",
message: err.message,
stackTrace: err.stackTrace
});
break;
case 401:
res.json({
title: "UNAUTHORIZED",
message: err.message,
stackTrace: err.stackTrace
});
break;
case 500:
res.json({
title: "SERVER ERROR",
message: err.message,
stackTrace: err.stackTrace
});
break;
default:
// console.log("res - ", res)
// console.log("req - ", req)
// console.log("err", err)
console.log("Error Handler working...");
break;
};
};
module.exports = errorHandler;
路线:
//Handle all requests - get, put, post and delete
// Import all express functionalities
const server = require("express");
// Create a router through express
const router = server.Router();
// - After creating all routes, we need to import controller functions
const {getAllContacts, createContact, getContact, updateContact, deleteContact} = require("../Controllers/allControllers");
// We need to route all the api calls
router.route("/").get(getAllContacts).post(createContact);
router.route("/:id").get(getContact).put(updateContact).delete(deleteContact);
// Expose all routes
module.exports = router;
猫鼬架构:
const mongoose = require("mongoose");
const contactSchema = mongoose.Schema({
name: {
type: String,
required: [true, "Please enter the name"]
},
email: {
type: String,
required: [true, "Please enter the email"]
},
phone: {
type: String,
required: [true, "Please enter the number"]
}
},
{
timestamps: true
});
module.exports = mongoose.model("Contact", contactSchema);
快乐路径有效,但是当我尝试发送未存储在我的集合(mongoDB)中的文档中的id时,api调用会继续运行。errorHandler 会自动调用默认情况并继续执行。第 6 行不记录任何内容。
这是我使用 node 和 express 的第一个项目。请让我知道如何解决此问题。
答:
0赞
myrn
7/2/2023
#1
if(!(await ret))
是错误的。await 关键字返回一个 promise,并且不在 if 块中使用。Ofc 第 6 行不记录任何内容,因为 ret 为 null。所以,像这样检查ret
if(!ret){
res.status(404);
throw new Error("Contact not found");
}
评论
0赞
Eraserhead_18
7/2/2023
我的初始代码只使用了 ret。我一直在等待,直到我意识到我错了。
0赞
Eraserhead_18
7/2/2023
实际问题根本不在于代码。它是我传递给 get 方法的 ID。我不知道 mongo 使用 24 个字符的固定长度字符串进行_id并且我试图传递 23 个字符的字符串,这导致了未知错误
0赞
myrn
7/2/2023
然后你应该用正则表达式检查id。像这样的东西和.const objectIdRegex=/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i
if(!objectIdRegex.test(req.params.id)) return new Error();
1赞
Eraserhead_18
7/2/2023
会的,谢谢你的帮助!
评论