簡體   English   中英

為什么catch()塊未在Objection.js查詢中運行,而then()始終運行,結果始終傳遞0或1?

[英]Why is catch() block not running in Objection.js queries and instead then() always runs passing either 0 or 1 as a result?

因此,當使用Objection.js運行查詢時,查詢將基於該查詢的成功或失敗返回數據,並且該數據將以0或1的形式傳遞到then()塊。這意味着要處理錯誤,我必須檢查假值,而不是在catch塊中發送響應。 難道我做錯了什么?

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);
        });
};
App is listening on port 3000.
1 then() block ran

您的代碼按預期工作。 之所以沒有進入catch塊,是因為沒有錯誤。 patch不返回該行。 它返回已更改的行數( 請參閱docs )。

我認為您真正想要的功能是patchAndFetchById請參閱docs )。 如果您擔心產生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);
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM