Javascript 为什么catch()块没有在objective.js查询中运行,而then()总是通过0或1运行?
因此,当使用Objective.js运行查询时,查询将根据所述查询的成功或失败返回数据,并将该数据作为0或1传递给then()块。对于错误处理,我必须检查错误值,而不是在catch块中发送响应。我做错什么了吗Javascript 为什么catch()块没有在objective.js查询中运行,而then()总是通过0或1运行?,javascript,sql,express,knex.js,objection.js,Javascript,Sql,Express,Knex.js,Objection.js,因此,当使用Objective.js运行查询时,查询将根据所述查询的成功或失败返回数据,并将该数据作为0或1传递给then()块。对于错误处理,我必须检查错误值,而不是在catch块中发送响应。我做错什么了吗 const editIndustry = async (req, res, next) => { const industry = await Industry.query().findById(req.params.industryId); if (!indust
const editIndustry = async (req, res, next) => {
const industry = await Industry.query().findById(req.params.industryId);
if (!industry) {
return res.status(404).json({
error: 'NotFoundError',
message: `industry not found`,
});
}
await industry
.$query()
.patch({ ...req.body })
.then(result => console.log(result, 'then() block'))
// never runs
.catch(err => {
console.log(err);
next(err);
});
};
您的代码正在按预期工作。它没有进入catch块的原因是没有错误<代码>修补程序不返回该行。它返回已更改的行数() 我认为您真正需要的函数是
patchAndFetchById
()。如果您担心生成404错误,可以通过throwIfNotFound追加。显然,如果在数据库中找不到,这将抛出,这将让您捕获。您可以捕获此错误的实例,以便发送正确的404响应。否则,您希望返回500。您需要从异议中请求NotFoundError
const { NotFoundError } = require('objection');
const Industry = require('<myIndustryModelLocation>');
const editIndustry = (req, res) => {
try {
return Industry
.query()
.patchAndFetchById(req.params.industryId, { ...req.body })
.throwIfNotFound();
} catch (err) {
if(err instanceof NotFoundError) {
return res.status(404).json({
error: 'NotFoundError',
message: `industry not found`,
});
}
return res.status(500);
}
};
const{NotFoundError}=require('objective');
const Industry=需要(“”);
const editIndustry=(请求、回复)=>{
试一试{
回归产业
.query()
.patchAndFetchById(req.params.industryId,{…req.body})
.throwIfNotFound();
}捕捉(错误){
if(err instanceof NotFoundError){
返回res.status(404.json)({
错误:“NotFoundError”,
消息:`未找到行业',
});
}
返回资源状态(500);
}
};
OP这里!谢谢你的帮助,我现在明白了,我的错误是返回值是rows。我使用了您的代码,但必须使用async await对其进行更新,以便它能够工作,因为调用是异步的。此外,我必须在响应中使用$query,因为我使用的是唯一的验证模块,该模块只能对$query执行验证。我理解-我没有包括async/await,因为Industry.query()
返回一个承诺,这意味着那里不需要async/await。如果你把它包括在内,它基本上只是包装了反对返回的承诺。但是,如果在请求中执行多个查询,则肯定需要使用async/await。很高兴知道你的问题已经解决了!你能把它标记为已解决吗?是的,我想,但我以前并没有真正理解它,现在我确实理解了一点。因此,我用一种更为合理的方式写了这封信。你说的“回报承诺”是什么意思?这不需要等待,或者。那么()?现在就解决,再次感谢!
const { NotFoundError } = require('objection');
const Industry = require('<myIndustryModelLocation>');
const editIndustry = (req, res) => {
try {
return Industry
.query()
.patchAndFetchById(req.params.industryId, { ...req.body })
.throwIfNotFound();
} catch (err) {
if(err instanceof NotFoundError) {
return res.status(404).json({
error: 'NotFoundError',
message: `industry not found`,
});
}
return res.status(500);
}
};