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

获取Cognito登录端点JSON响应并渲染UI错误信息的方法咨询

解决Cognito登录错误信息展示方案

实现步骤

  • 新增错误状态用于存储登录异常信息
  • 登录请求发起前清空历史错误,避免残留展示
  • 在authenticateUser的onFailure回调中捕获Cognito返回的错误对象,提取错误码或错误提示存入状态
  • 在表单UI中加入错误信息渲染逻辑,错误状态非空时展示提示

核心代码修改

1. 新增错误状态

// 在原有状态后新增
const [errorMessage, setErrorMessage] = useState<string | null>(null);

2. 改造onSubmit逻辑

const onSubmit = (event) => {
  event.preventDefault();
  // 提交前清空历史错误
  setErrorMessage(null);

  const user = new CognitoUser({
    Username: username,
    Pool: UserPool,
  });

  const authDetails = new AuthenticationDetails({
    Username: username,
    Password: password,
  });

  user.authenticateUser(authDetails, {
    onSuccess: (data) => {
      console.log("onSuccess:", data);
      // 登录成功后自行补充页面跳转等逻辑
    },
    onFailure: (err) => {
      console.log("onFailure:", err);
      // 可直接使用err.message,也可根据err.code自定义友好提示
      const errMsgMap: Record<string, string> = {
        "NotAuthorizedException": "用户名或密码错误,请重试",
        "UserNotFoundException": "账号不存在,请先注册",
        "UserNotConfirmedException": "账号未验证,请先完成邮箱/手机号验证",
        "PasswordResetRequiredException": "需重置密码后才能登录"
      }
      setErrorMessage(errMsgMap[err.code] || err.message || "登录失败,请稍后重试");
    },
    newPasswordRequired: (data) => {
      console.log("newPasswordRequired:", data);
      // 新用户需重置密码的逻辑自行补充
    },
  });
};

3. UI中加入错误提示渲染

在密码输入框和登录按钮之间加入错误展示代码:

<TextField
  id="standard-basic"
  label="Password"
  variant="standard"
  type="password"
  value={password}
  onChange={(e) => {
    setPassword(e.target.value);
  }}
/>
{/* 新增错误提示 */}
{errorMessage && (
  <p style={{ color: "#d32f2f", fontSize: "14px", margin: "10px 0 0 0" }}>
    {errorMessage}
  </p>
)}
<div className="forgot-checkbox">

说明

amazon-cognito-identity-js已经将Cognito的接口响应自动解析为结构化错误对象,你不需要自行解析JSON,直接从回调的err参数中取code(错误码)、message(错误描述)属性即可使用,你截图中的响应内容就是这个err对象的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:36:03