【问题标题】:Where do I handle feathersjs/socketio-client connection error我在哪里处理 feathersjs/socketio-client 连接错误
【发布时间】:2019-04-10 23:13:05
【问题描述】:

我在后端使用带有 socketio 的羽毛。客户正在倾听,一切正常。

我想处理“服务器无响应”错误,但找不到在哪里可以处理?

服务器抛出的错误:

"Unhandled promise rejection 
Object { type: "FeathersError", name: "Timeout", message: "Timeout of 5000ms exceeded calling find on newsfeed", code: 408, className: "timeout", data: {…}, errors: {}, stack: "FeathersError@webpack-internal:///./node_modules/@feathersjs/errors/lib/index.js:58:19\nTimeout@webpack-internal:///./node_modules/@feathersjs/errors/lib/index.js:135:3\nsend/</timeoutId<@webpack-internal:///./node_modules/@feathersjs/transport-commons/lib/client.js:66:9\n" }"

没错,'promise' 没有处理!我在哪里处理?

我尝试在每一行添加 catch 只是为了看看什么有效但没有成功:

import feathers from '@feathersjs/feathers'
import socketio from '@feathersjs/socketio-client'
import io from 'socket.io-client'

const socket = io('http://localhost:3030/', {transports: ['websocket']});
socket.on("connect_failed", er=>console.error('Error connecting to server: ', er));
const restApi = feathers()
  .configure(socketio(socket));

try {
  restApi.service('/newsfeed');
  restApi.on("connect_failed", er=>console.error('Error connecting to server: ', er));

}
catch (er) {
    console.error('Error connecting to server: ', er)
}

export default restApi

【问题讨论】:

    标签: socket.io feathersjs


    【解决方案1】:

    超时错误来自特定请求,因此无论您在哪里发出请求,您都必须处理它。

    restApi.service('/newsfeed').find()

    如果您使用的是 async/await,则可以将服务调用包装在 try/catch 中,或者我个人最喜欢的只是在调用上添加一个 catch;

    // try/catch
    try {
      const response= await restApi.service('/newsfeed').find();
    catch(e) {
      // handle e
    }
    
    //just use catch
    const response= await restApi.service('/newsfeed').find().catch(e => {
      // handle e
    });
    

    如果你使用 Promise,只需使用 catch:

    restApi.service('/newsfeed').find().then(response => {
      // handle response
    }).catch(e => {
      // handle e
    });
    

    【讨论】:

    • 你是对的,但在这种情况下,它是关于连接的。在我使用find(或getpost等)的地方,当然我catch作为服务器发回了几种类型的错误,如禁止/用户未通过身份验证等,并带有自定义错误代码。
    • 我有一个组件订阅来自套接字客户端的disconnectconnect_timeoutconnectreconnect 事件(在您的情况下为restApi.io)。它在 API 脱机时处理显示/隐藏消息。所有事件都列在这里:socket.io/docs/client-api/…
    • 酷!我也有一个! (使用 Vue - 它隐藏屏幕并仅显示以下状态:互联网连接和 API 服务器可用性。当我在常规调用中收到 404 或其他特定错误时,我将其打开。但在这里我不知道该怎么做,如何从 socket.io 中捕获“404”(或类似的)。我尝试引导“connect_error”失败。
    • 您只能监听 socket.io 文档中列出的事件。这些都是连接级别的事件。要“侦听” 404 和其他错误,您可以捕获这些错误并将错误传达给您的其他组件,或者使用错误挂钩。 docs.feathersjs.com/api/hooks.html#application-hooks
    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 2019-05-30
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多