How to catch websocket connection error

Connect to the QWebSocket error signal, before opening the socket.

QWebSocket* pWebSocket = new QWebSocket;
connect(pWebSocket, &QWebSocket::error, [=](QAbstractSocket::SocketError error)
{
    // Handle error here...
    qDebug() << pWebSocket->errorString();
}

pWebSocket->open("wss://192.123.1.44:8087");

Note that this connection uses a lambda function, which requires C++ 11. Connection to a slot in the usual manner will also work.

Without C++ 11, use a standard (Qt 5) connection: -

class MyClass : public QObject
{
   Q_OBJECT

   public:
       MyClass(QUrl url);

   protected slots:
       void Error(QAbstractSocket::SocketError error);

   private:
       QWebSocket* pWebSocket;
};


MyClass::MyClass(QUrl url)
{        
    QWebSocket* pWebSocket = new QWebSocket;
    connect(pWebSocket, &QWebSocket::error, pMyClass, &MyClass::Error);
    m_webSocket->open(url);
}

As QObject::connect returns a QMetaObjectConnection, which contains an overloaded bool operator, you can check the return from the call to connect, to ensure that a valid signal and slot was found, and valid arguments provided: -

// Old-style connection
if(!connect(m_webSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onWebSocketError(QAbstractSocket::SocketError))) )
{
    qDebug() << "Failed to connect to QWebSocket::error" <<  endl;
}

However, this is largely redundant, as a failed connection usually produces debug output informing you of this issue, from within Qt's connect call.

NOTE, in the old-style connection syntax, the argument list does not name the arguments, only the type is provided. Adding a name will produce a failed connection.


As described in the documentation:

Note: Signal error is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function pointer as shown in this example:

connect(webSocket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
[=](QAbstractSocket::SocketError error){ /* ... */ });

Of course, instead of lambda function, you could connect to a normal one, but the QOverload part is important.

Tags:

C++

Qt

Websocket