You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Knex Promise封装CoreModel的catch执行后控制器逻辑异常咨询

Why Your Controller's Error Handling Isn't Triggered After CoreModel Catches an Error

Hey there! Let's break down why your controller's catch block isn't behaving as expected, even though the catch in your CoreModel runs correctly.

The Root Cause

In your CoreModel.add() method, when an error occurs, your catch block captures it and returns the result of getMsg(300, err). Here's the critical detail: when you return any value from a catch block, the Promise chain switches from a rejected state to a resolved state.

By the time the Promise reaches your controller, it’s no longer in an error state—it’s resolved with the value from getMsg(). That’s why your controller’s then block runs (receiving the error message as the id parameter) instead of the catch block.

Fixes to Try

Option 1: Re-throw the Error in CoreModel

If you want the controller’s catch block to handle the error, you can capture the error in CoreModel (for logging or initial processing) and then re-throw it. This keeps the Promise chain in a rejected state:

add(payload, table) {
  return this.conn()(table ? table : this.table)
    .insert(payload)
    .then(id => id)
    .catch(err => {
      // Optional: Log the error for debugging first
      console.error('Database insert failed:', err);
      // Re-throw the custom error so downstream can catch it
      throw getMsg(300, err);
    })
    .finally(() => {
      this.conn().destroy()
    });
}

Now your controller’s catch block will receive the getMsg() result as the error.

Option 2: Return an Error-Flagged Object

If you prefer to handle error messaging in CoreModel but still let the controller know it’s an error, return an object with a clear success flag:

// In CoreModel.add()
.catch(err => {
  return { success: false, error: getMsg(300, err) };
})

Then in your controller, check the flag and trigger the catch block manually:

return this.Users.add(request.payload.users)
  .then(result => {
    if (!result.success) {
      throw result.error; // This will trigger the controller's catch
    }
    return result;
  })
  .catch(err => err);

A Quick Side Note

Also, be aware that calling this.conn().destroy() in the finally block destroys the database connection every time you run add(). Depending on how your conn() method works, this could mean creating and tearing down a connection on every request—which might hurt performance. You might want to look into connection pooling instead if you haven’t already!

内容的提问来源于stack exchange,提问作者Rip3rs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:52:45