LibresapiLocalClient improve error handling

This commit is contained in:
Gioacchino Mazzurco 2017-04-10 15:00:14 +02:00
parent c3ba5511d8
commit 29a3d105c4
2 changed files with 29 additions and 7 deletions

View File

@ -22,13 +22,14 @@
#include <QJSEngine>
#include <QtDebug>
void LibresapiLocalClient::openConnection(QString socketPath)
void LibresapiLocalClient::openConnection(const QString& socketPath)
{
connect(& mLocalSocket, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(socketError(QLocalSocket::LocalSocketError)));
connect(& mLocalSocket, SIGNAL(readyRead()),
this, SLOT(read()));
mLocalSocket.connectToServer(socketPath);
mSocketPath = socketPath;
socketConnectAttempt();
}
int LibresapiLocalClient::request( const QString& path, const QString& jsonData,
@ -44,13 +45,24 @@ int LibresapiLocalClient::request( const QString& path, const QString& jsonData,
data.append(path); data.append('\n');
data.append(jsonData); data.append('\n');
processingQueue.enqueue(PQRecord(path, jsonData, callback));
return mLocalSocket.write(data);
int ret = mLocalSocket.write(data);
if(ret < 0) socketError(mLocalSocket.error());
return ret;
}
void LibresapiLocalClient::socketError(QLocalSocket::LocalSocketError)
void LibresapiLocalClient::socketError(QLocalSocket::LocalSocketError error)
{
qCritical() << __PRETTY_FUNCTION__ << "Socket Eerror! "
qCritical() << __PRETTY_FUNCTION__ << "Socket error! " << error
<< mLocalSocket.errorString();
if(mLocalSocket.state() == QLocalSocket::UnconnectedState &&
!mConnectAttemptTimer.isActive())
{
qDebug() << __PRETTY_FUNCTION__ << "Socket:" << mSocketPath
<< "is not connected, scheduling a connect attempt again";
mConnectAttemptTimer.start();
}
}
void LibresapiLocalClient::read()

View File

@ -23,6 +23,7 @@
#include <QLocalSocket>
#include <QQueue>
#include <QJSValue>
#include <QTimer>
class LibresapiLocalClient : public QObject
{
@ -33,11 +34,17 @@ public:
#ifdef QT_DEBUG
reqCount(0), ansCount(0), mDebug(true),
#endif // QT_DEBUG
mLocalSocket(this) {}
mLocalSocket(this)
{
mConnectAttemptTimer.setSingleShot(true);
mConnectAttemptTimer.setInterval(500);
connect(&mConnectAttemptTimer, SIGNAL(timeout()),
this, SLOT(socketConnectAttempt()));
}
Q_INVOKABLE int request( const QString& path, const QString& jsonData = "",
QJSValue callback = QJSValue::NullValue );
Q_INVOKABLE void openConnection(QString socketPath);
Q_INVOKABLE void openConnection(const QString& socketPath);
#ifdef QT_DEBUG
Q_PROPERTY(bool debug READ debug WRITE setDebug NOTIFY debugChanged)
@ -51,6 +58,8 @@ public:
#endif // QT_DEBUG
private:
QTimer mConnectAttemptTimer;
QString mSocketPath;
QLocalSocket mLocalSocket;
struct PQRecord
@ -68,6 +77,7 @@ private:
QQueue<PQRecord> processingQueue;
private slots:
void socketConnectAttempt() { mLocalSocket.connectToServer(mSocketPath); }
void socketError(QLocalSocket::LocalSocketError error);
void read();