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

Node.js中如何将Service层的错误信息传递到Controller层

问题修复方案

核心问题根因

  • Controller层错误处理逻辑错误:捕获到Service抛出的错误后,直接返回500状态码,且将整个Error实例作为message返回,Error实例序列化后无法正常展示错误文本;同时没有区分业务错误和系统错误,邮箱已存在属于业务校验错误,应该返回400状态码而非500。
  • Service层用户保存操作使用回调写法:若保存过程触发错误,无法被外层try/catch捕获,会导致错误丢失。

修复步骤

1. 修改Controller层错误处理逻辑

将原有catch块代码替换为以下内容:

catch (error) {
  console.log(error);
  const errMsg = error.message
  // 业务校验错误返回400状态码
  if (errMsg === "This email is already taken") {
    return res.status(400).json({ message: "该邮箱已被注册" })
  }
  // 其他系统错误返回500状态码
  res.status(500).json({message: "服务器内部错误,请稍后重试" })
}

2. 优化Service层异步操作

将Service中newUser.save的回调写法改为await写法,保证所有异步错误都能被外层捕获:

// 替换原有newUser.save的回调代码
await newUser.save();
// 邮件发送不阻塞主流程,单独捕获错误避免影响注册逻辑
transporter.sendMail({
  to: newUser.email,
  from: process.env.SCHOOLSCOOL_EMAIL,
  subject: "注册成功!",
  html: `<p>欢迎加入School's Cool ${newUser.firstName} ${newUser.lastName},<br>
          <br>请登录使用网页应用。<br><br>谢谢。</p>`,
}).catch(err => console.log("邮件发送失败:", err));

修改完成后,邮箱重复的校验错误就能正常返回到前端,且状态码符合RESTful规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:45:02