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

如何在npm版aws-amplify中无报错检测是否存在session

你可以通过try/catch包裹Auth.currentSession调用实现需求,该API的原生设计就是无有效会话时抛出异常来告知状态,只要捕获异常不对外抛出即可避免运行时报错。

基础实现代码

try {
  const session = await Auth.currentSession();
  // 已登录逻辑
} catch (error) {
  // 未登录逻辑,无需额外抛出错误即可
}

适配你需要的if/else判断写法

可以封装成通用工具函数,业务侧直接判断返回值即可:

// 全局封装工具方法
async function checkAuthSession() {
  try {
    return await Auth.currentSession();
  } catch (err) {
    return null;
  }
}

// 业务侧调用
const session = await checkAuthSession();
if (session) {
  /* 已登录 */
} else {
  /* 未登录 */
}

可选优化

如果需要屏蔽控制台默认输出的No current user错误日志,可以调整Amplify日志级别:

import { Logger } from 'aws-amplify';
Logger.LOG_LEVEL = 'WARN'; // 仅输出警告及以上级别的日志,屏蔽Auth类的ERROR级普通状态日志

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:06:04