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

Angular 17+中AWSAppSyncClient Websocket授权错误无法触发订阅错误处理器

Angular 17+ 中 AWS AppSync 订阅网络错误无法触发错误处理器

环境与配置

使用Angular 17.1.3,通过aws-appsync v4.1.10连接AWS AppSync,认证方式为OPENID_CONNECT,配置代码如下:

client!: AWSAppSyncClient<any>;

this.client = new AWSAppSyncClient({
    url: 'https://<AppSync EndPoint domain>/graphql',
    region: '<Region>',
    auth: {
        type: 'OPENID_CONNECT',
        jwtToken: async () => await this.AuthProvider.accessToken()
    },
    disableOffline: true,
});

订阅代码:

this.client.hydrated().then((client: any) => {
    client.subscribe({ query:<GQLQUERY> }).subscribe({
        next: (data: any) => {
            console.log('data', data);
        },
        error: (error: any) => {
            console.error('error', error);
        },
    });
});

问题现象

浏览器开发者工具的WebSocket消息面板已显示网络错误,但订阅的error回调长时间无法触发。

依赖版本

"@angular/common": "^17.1.3",
"@angular/compiler": "^17.1.3",
"@angular/core": "^17.1.3",
"@angular/platform-browser": "^17.1.3",
"@angular/platform-browser-dynamic": "^17.1.3",
"@angular/router": "^17.1.3",
"apollo-client": "^2.6.10",
"aws-appsync": "^4.1.10",
"graphql": "^14.7.0",
"graphql-tag": "^2.12.6",
"rxjs": "~7.8.1",

解决方案

  • 检查版本兼容性
    当前aws-appsync v4.1.10与RxJS 7.x可能存在适配问题,可尝试降级RxJS到6.x(如6.6.7),或升级aws-appsync至最新稳定版,同步确认Apollo相关依赖版本匹配。

  • 手动监听WebSocket底层错误
    绕过订阅Observable的错误回调,直接监听WebSocket客户端的错误事件:

    this.client.hydrated().then((client: any) => {
        const sub = client.subscribe({ query: <GQLQUERY> }).subscribe({
            next: (data: any) => console.log('data', data),
            error: (error: any) => console.error('error', error),
        });
        // 监听WebSocket原生错误
        if (client.wsClient) {
            client.wsClient.on('error', (err: any) => {
                console.error('WebSocket底层错误:', err);
                // 在这里执行自定义错误处理逻辑
                sub.unsubscribe();
            });
        }
    });
    
  • 验证认证Token有效性
    在jwtToken回调中添加日志,确认Token获取正常且未过期:

    auth: {
        type: 'OPENID_CONNECT',
        jwtToken: async () => {
            const token = await this.AuthProvider.accessToken();
            console.log('当前使用的JWT Token:', token?.substring(0, 50) + '...');
            return token;
        }
    },
    
  • 启用调试日志
    开启aws-appsync的调试模式,获取内部运行日志:

    this.client = new AWSAppSyncClient({
        // 原有配置...
        debug: true
    });
    
  • 检查AppSync端配置
    确认AppSync的订阅规则配置正确,且当前OIDC认证用户拥有订阅权限,避免因权限问题导致连接静默失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:55:09