]> granicus.if.org Git - icinga2/commitdiff
Use STL exceptions as far as possible.
authorGunnar Beutner <gunnar.beutner@netways.de>
Sat, 26 May 2012 19:30:04 +0000 (21:30 +0200)
committerGunnar Beutner <gunnar.beutner@netways.de>
Sat, 26 May 2012 19:30:04 +0000 (21:30 +0200)
20 files changed:
base/application.cpp
base/application.h
base/configobject.cpp
base/dictionary.h
base/exception.cpp
base/exception.h
base/socket.cpp
base/socket.h
base/tcpclient.cpp
base/tcpsocket.cpp
base/tlsclient.cpp
base/utility.cpp
base/variant.cpp
components/configfile/configfilecomponent.cpp
components/discovery/discoverycomponent.cpp
icinga/endpointmanager.cpp
icinga/icingaapplication.cpp
icinga/jsonrpcendpoint.cpp
jsonrpc/messagepart.cpp
jsonrpc/netstring.cpp

index d1c4fd5d1c2255723337769425b208f1c1a4ca50..0a3210c955ff40fcea93c16333ca6b111a648283 100644 (file)
@@ -230,7 +230,7 @@ Component::Ptr Application::LoadComponent(const string& path,
 #endif /* _WIN32 */
 
        if (hModule == NULL)
-               throw ComponentLoadException("Could not load module");
+               throw runtime_error("Could not load module");
 
 #ifdef _WIN32
        pCreateComponent = (CreateComponentFunction)GetProcAddress(hModule,
@@ -245,8 +245,8 @@ Component::Ptr Application::LoadComponent(const string& path,
 #endif /* _WIN32 */
 
        if (pCreateComponent == NULL)
-               throw ComponentLoadException("Loadable module does not "
-                   "contain CreateComponent function");
+               throw runtime_error("Loadable module does not contain "
+                   "CreateComponent function");
 
        component = Component::Ptr(pCreateComponent());
        component->SetConfig(componentConfig);
@@ -368,7 +368,7 @@ string Application::GetExeDirectory(void) const
                        free(PathEnv);
 
                        if (!FoundPath)
-                               throw Exception("Could not determine executable path.");
+                               throw runtime_error("Could not determine executable path.");
                }
        }
 
index 5b22db9f678bf986e90a2d1365c45a0ab7f42fcf..c8ee5afd14fee1ccae10b5b077d27dd4e8e07a5a 100644 (file)
@@ -24,8 +24,6 @@ namespace icinga {
 
 class Component;
 
-DEFINE_EXCEPTION_CLASS(ComponentLoadException);
-
 /**
  * Abstract base class for applications.
  *
index 65ac039416ff6cf2a267dd0df5ef2ae8d8726443..d0a1ba49ef7cf37bc84bc04dacb6033498ea980e 100644 (file)
@@ -42,7 +42,7 @@ ConfigObject::ConfigObject(const string& type, const string& name)
 void ConfigObject::SetHive(const ConfigHive::WeakPtr& hive)
 {
        if (m_Hive.lock())
-               throw InvalidArgumentException("Config object already has a parent hive.");
+               throw logic_error("Config object already has a parent hive.");
 
        m_Hive = hive;
 }
index 5cf00ac9fc62ffdcd5051c80f55f4c70dcee066c..253b6fbe7506d2fe9ae6afa43a71b1d4f9b3ff96 100644 (file)
@@ -73,7 +73,7 @@ public:
 
                *value = dynamic_pointer_cast<Dictionary>(object);
                if (!*value)
-                       throw InvalidCastException();
+                       throw runtime_error("Object is not a dictionary.");
 
                return true;
        }
index 5a6dcc95b03b1bbc09b8c112c97bbb6d2db1cd9b..00858c1f23d2b4160b999a3500080a63a138afdf 100644 (file)
 
 using namespace icinga;
 
-/**
- * Default constructor for the Exception class.
- */
-Exception::Exception(void)
-{
-       m_Code = 0;
-       m_Message = NULL;
-}
-
-/**
- * Constructor for the exception class.
- *
- * @param message A message describing the exception.
- */
-Exception::Exception(const char *message)
-{
-       m_Code = 0;
-       m_Message = NULL;
-       SetMessage(message);
-}
-
-/**
- * Destructor for the Exception class. Must be virtual for RTTI to work.
- */
-Exception::~Exception(void) throw()
-{
-       Memory::Free(m_Message);
-}
-
 /**
  * Retrieves the error code for the exception.
  *
@@ -75,7 +46,7 @@ void Exception::SetCode(int code)
  *
  * @returns The description.
  */
-const char *Exception::GetMessage(void) const
+string Exception::GetMessage(void) const
 {
        return m_Message;
 }
@@ -87,7 +58,7 @@ const char *Exception::GetMessage(void) const
  */
 const char *Exception::what(void) const throw()
 {
-       return GetMessage();
+       return GetMessage().c_str();
 }
 
 /**
@@ -95,10 +66,9 @@ const char *Exception::what(void) const throw()
  *
  * @param message The description.
  */
-void Exception::SetMessage(const char *message)
+void Exception::SetMessage(string message)
 {
-       Memory::Free(m_Message);
-       m_Message = Memory::StrDup(message);
+       m_Message = message;
 }
 
 #ifdef _WIN32
index 3ab702e64e6217d6ca020b50df56a76b21a3ab8b..d614eb7cba7cfe5e68934d55032ffe5355c7cc01 100644 (file)
@@ -31,21 +31,35 @@ namespace icinga
 class I2_BASE_API Exception : public virtual std::exception
 {
 public:
-       Exception(void);
-       Exception(const char *message);
-       virtual ~Exception(void) throw();
+       Exception(void)
+           : m_Message(), m_Code(0)
+       { }
+
+       Exception(string message)
+           : m_Message(message), m_Code(0)
+       { }
+
+       Exception(string message, int code)
+           : m_Message(message), m_Code(code)
+       { }
+
+       /**
+        * Destructor for the Exception class. Must be virtual for RTTI to work.
+        */
+       virtual ~Exception(void) throw()
+       { }
 
        int GetCode(void) const;
-       const char *GetMessage(void) const;
+       string GetMessage(void) const;
 
        virtual const char *what(void) const throw();
 
 protected:
        void SetCode(int code);
-       void SetMessage(const char *message);
+       void SetMessage(string message);
 
 private:
-       char *m_Message;
+       string m_Message;
        int m_Code;
 };
 
@@ -54,13 +68,11 @@ private:
        {                                                               \
        public:                                                         \
                inline klass(void) : Exception()                        \
-               {                                                       \
-               }                                                       \
+               { }                                                     \
                                                                        \
-               inline klass(const char *message)                       \
+               inline klass(string message)                            \
                    : Exception(message)                                \
-               {                                                       \
-               }                                                       \
+               { }                                                     \
        }
 
 /**
@@ -71,22 +83,6 @@ private:
  */
 DEFINE_EXCEPTION_CLASS(NotImplementedException);
 
-/**
- * An exception that is thrown when an argument to
- * a function is invalid.
- *
- * @ingroup base
- */
-DEFINE_EXCEPTION_CLASS(InvalidArgumentException);
-
-/**
- * An exception that is thrown when a cast yields
- * an invalid result.
- *
- * @ingroup base
- */
-DEFINE_EXCEPTION_CLASS(InvalidCastException);
-
 #ifdef _WIN32
 /**
  * A Win32 error encapsulated in an exception.
@@ -101,11 +97,8 @@ public:
         * @param errorCode A Win32 error code.
         */
        inline Win32Exception(const string& message, int errorCode)
-       {
-               string msg = message + ": " + FormatErrorCode(errorCode);
-               SetMessage(msg.c_str());
-               SetCode(errorCode);
-       }
+           : Exception(message + ": " + FormatErrorCode(errorCode), errorCode)
+       { }
 
        /**
         * Returns a string that describes the Win32 error.
@@ -130,11 +123,8 @@ public:
         * @param errorCode A Posix (errno) error code.
         */
        inline PosixException(const string& message, int errorCode)
-       {
-               string msg = message + ": " + FormatErrorCode(errorCode);
-               SetMessage(msg.c_str());
-               SetCode(errorCode);
-       }
+           : Exception(message + ": " + FormatErrorCode(errorCode), errorCode)
+       { }
 
        /**
         * Returns a string that describes the Posix error.
@@ -158,10 +148,8 @@ public:
         * @param errorCode An OpenSSL error code.
         */
        inline OpenSSLException(const string& message, int errorCode)
-       {
-               string msg = message + ": " + FormatErrorCode(errorCode);
-               SetMessage(msg.c_str());
-       }
+           : Exception(message + ": " + FormatErrorCode(errorCode), errorCode)
+       { }
 
        /**
         * Returns a string that describes the OpenSSL error.
index a876b3dcbda4c947f336e04a64d21ee7bb5388b4..dfe44994b2bd0e01d3268d240407af47cbefed84 100644 (file)
@@ -167,17 +167,17 @@ int Socket::GetLastSocketError(void)
  * Handles a socket error by calling the OnError event or throwing an exception
  * when there are no observers for the OnError event.
  *
- * @param exception An exception.
+ * @param ex An exception.
  */
-void Socket::HandleSocketError(const Exception& exception)
+void Socket::HandleSocketError(const exception& ex)
 {
        if (OnError.HasObservers()) {
-               SocketErrorEventArgs sea(exception);
+               SocketErrorEventArgs sea(ex);
                OnError(sea);
 
                Close();
        } else {
-               throw exception;
+               throw ex;
        }
 }
 
@@ -226,7 +226,8 @@ string Socket::GetAddressFromSockaddr(sockaddr *address, socklen_t len)
        char service[NI_MAXSERV];
 
        if (getnameinfo(address, len, host, sizeof(host), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV) < 0)
-               throw InvalidArgumentException(); /* TODO: throw proper exception */
+               throw SocketException("getnameinfo() failed",
+                   GetLastSocketError());
 
        stringstream s;
        s << "[" << host << "]:" << service;
index 1d56c23d75eda4805c93ebf3d8df92b804e7b412..75c70d1c1df2e1ef2633d7f469734d0de0fd2ae8 100644 (file)
@@ -29,10 +29,10 @@ namespace icinga {
  */
 struct I2_BASE_API SocketErrorEventArgs : public EventArgs
 {
-       const Exception& Error;
+       const exception& Exception;
 
-       SocketErrorEventArgs(const Exception& exception)
-           : Error(exception) { }
+       SocketErrorEventArgs(const exception& ex)
+           : Exception(ex) { }
 };
 
 /**
@@ -78,7 +78,7 @@ protected:
 
        int GetError(void) const;
        static int GetLastSocketError(void);
-       void HandleSocketError(const Exception& exception);
+       void HandleSocketError(const exception& ex);
 
        virtual void CloseInternal(bool from_dtor);
 
index 0045cff5ade171b2f53c4c4cb772f0d07a2e2334..0308e4844e09a1ca32b53c0cf279d75de3eef2ff 100644 (file)
@@ -110,7 +110,8 @@ void TcpClient::Connect(const string& node, const string& service)
        freeaddrinfo(result);
 
        if (fd == INVALID_SOCKET)
-               HandleSocketError(InvalidArgumentException());
+               HandleSocketError(runtime_error(
+                   "Could not create a suitable socket."));
 }
 
 /**
index 2cce586d1e8886dbfcf573d5be86f18822e059af..d2932e9a6eac9443864a1dcae39cca6d9dd37803 100644 (file)
@@ -116,5 +116,6 @@ void TcpSocket::Bind(string node, string service, int family)
        freeaddrinfo(result);
 
        if (fd == INVALID_SOCKET)
-               HandleSocketError(InvalidArgumentException());
+               HandleSocketError(runtime_error(
+                   "Could not create a suitable socket."));
 }
index a9e1ebc807bc794450a889170618ff5e77240370..2669b4d26e9a631dba5f4f60c53d720c89745420 100644 (file)
@@ -80,7 +80,7 @@ void TlsClient::Start(void)
                throw OpenSSLException("SSL_new failed", ERR_get_error());
 
        if (!GetClientCertificate())
-               throw InvalidArgumentException("No X509 client certificate was specified.");
+               throw logic_error("No X509 client certificate was specified.");
 
        if (!m_SSLIndexInitialized) {
                m_SSLIndex = SSL_get_ex_new_index(0, (void *)"TlsClient", NULL, NULL, NULL);
index a1f404d1f076d7f2c5cf400e505b794fba837d84..fa89e7d75d6ec4f1284e7ce64e160291380be0f2 100644 (file)
@@ -34,7 +34,7 @@ void Utility::Daemonize(void) {
 
        pid = fork();
        if (pid < 0)
-               throw PosixException("fork failed", errno);
+               throw PosixException("fork() failed", errno);
 
        if (pid)
                exit(0);
@@ -42,7 +42,7 @@ void Utility::Daemonize(void) {
        fd = open("/dev/null", O_RDWR);
 
        if (fd < 0)
-               throw PosixException("open failed", errno);
+               throw PosixException("open() failed", errno);
 
        if (fd != 0)
                dup2(fd, 0);
@@ -57,7 +57,7 @@ void Utility::Daemonize(void) {
                close(fd);
 
        if (setsid() < 0)
-               throw PosixException("setsid failed", errno);
+               throw PosixException("setsid() failed", errno);
 #endif
 }
 
@@ -94,13 +94,13 @@ shared_ptr<SSL_CTX> Utility::MakeSSLContext(string pubkey, string privkey, strin
        SSL_CTX_set_mode(sslContext.get(), SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
 
        if (!SSL_CTX_use_certificate_chain_file(sslContext.get(), pubkey.c_str()))
-               throw InvalidArgumentException("Could not load public X509 key file.");
+               throw OpenSSLException("Could not load public X509 key file", ERR_get_error());
 
        if (!SSL_CTX_use_PrivateKey_file(sslContext.get(), privkey.c_str(), SSL_FILETYPE_PEM))
-               throw InvalidArgumentException("Could not load private X509 key file.");
+               throw OpenSSLException("Could not load private X509 key file", ERR_get_error());
 
        if (!SSL_CTX_load_verify_locations(sslContext.get(), cakey.c_str(), NULL))
-               throw InvalidArgumentException("Could not load public CA key file.");
+               throw OpenSSLException("Could not load public CA key file", ERR_get_error());
 
        return sslContext;
 }
@@ -118,7 +118,7 @@ string Utility::GetCertificateCN(const shared_ptr<X509>& certificate)
        int rc = X509_NAME_get_text_by_NID(X509_get_subject_name(certificate.get()), NID_commonName, buffer, sizeof(buffer));
 
        if (rc == -1)
-               throw InvalidArgumentException("X509 certificate has no CN attribute.");
+               throw OpenSSLException("X509 certificate has no CN attribute", ERR_get_error());
 
        return buffer;
 }
index 3c906df27499cb3d71e6b2463cbab76d9922eda0..914bfdb14cb46338e8e0fa448a232bc2433ed770 100644 (file)
@@ -39,7 +39,7 @@ void Variant::Convert(VariantType newType) const
        }
 
        // TODO: convert variant data
-       throw InvalidArgumentException("Invalid variant conversion.");
+       throw runtime_error("Invalid variant conversion.");
 }
 
 /**
index 08b52233eb1401abb9721c73d63044d747ea4d90..d89b8c0bedc0dd43ae2e626b1abaf704356a07b7 100644 (file)
@@ -36,11 +36,11 @@ void ConfigFileComponent::Start(void)
 
        string filename;
        if (!GetConfig()->GetProperty("configFilename", &filename))
-               throw InvalidArgumentException("Missing 'configFilename' property");
+               throw logic_error("Missing 'configFilename' property");
 
        fp.open(filename.c_str(), ifstream::in);
        if (fp.fail())
-               throw ConfigParserException("Could not open config file");
+               throw runtime_error("Could not open config file");
        
        GetIcingaApplication()->Log("Reading config file: " + filename);
 
@@ -49,7 +49,7 @@ void ConfigFileComponent::Start(void)
                char *buffer = (char *)fifo->GetWriteBuffer(&bufferSize);
                fp.read(buffer, bufferSize);
                if (fp.bad())
-                       throw ConfigParserException("Could not read from config file");
+                       throw runtime_error("Could not read from config file");
                fifo->Write(NULL, fp.gcount());
        }
 
index 815f35557e5168f7da7be817e720503b298692f8..9965353bfbbc9b3a0e601b365cb3c3ed9ed5b59f 100644 (file)
@@ -363,7 +363,7 @@ bool DiscoveryComponent::HasMessagePermission(Dictionary::Ptr roles, string mess
 
                Dictionary::Ptr permissions = dynamic_pointer_cast<Dictionary>(object);
                if (!permissions)
-                       throw InvalidCastException();
+                       throw runtime_error("Object is not a dictionary.");
 
                for (DictionaryIterator is = permissions->Begin(); is != permissions->End(); is++) {
                        if (Utility::Match(is->second.GetString(), message))
@@ -404,9 +404,8 @@ void DiscoveryComponent::ProcessDiscoveryMessage(string identity, DiscoveryMessa
                Object::Ptr object;
                if (endpointConfig->GetProperty("roles", &object)) {
                        roles = dynamic_pointer_cast<Dictionary>(object);
-
                        if (!roles)
-                               throw InvalidCastException();
+                               throw runtime_error("Object is not a dictionary.");
                }
        }
 
index 2b59db4f4d072dab5d57e11b78a346576537c28f..728285b110ac4a4cab4b0030c75081a8824c3eae 100644 (file)
@@ -70,7 +70,7 @@ shared_ptr<SSL_CTX> EndpointManager::GetSSLContext(void) const
 void EndpointManager::AddListener(string service)
 {
        if (!GetSSLContext())
-               throw InvalidArgumentException("SSL context is required for AddListener()");
+               throw logic_error("SSL context is required for AddListener()");
 
        stringstream s;
        s << "Adding new listener: port " << service;
@@ -151,7 +151,7 @@ void EndpointManager::UnregisterServer(JsonRpcServer::Ptr server)
 void EndpointManager::RegisterEndpoint(Endpoint::Ptr endpoint)
 {
        if (!endpoint->IsLocal() && endpoint->GetIdentity() != "")
-               throw InvalidArgumentException("Identity must be empty.");
+               throw invalid_argument("Identity must be empty.");
 
        endpoint->SetEndpointManager(static_pointer_cast<EndpointManager>(shared_from_this()));
        m_Endpoints.push_back(endpoint);
@@ -220,11 +220,11 @@ void EndpointManager::SendMulticastMessage(Endpoint::Ptr sender,
 {
        string id;
        if (message.GetID(&id))
-               throw InvalidArgumentException("Multicast requests must not have an ID.");
+               throw invalid_argument("Multicast requests must not have an ID.");
 
        string method;
        if (!message.GetMethod(&method))
-               throw InvalidArgumentException("Message is missing the 'method' property.");
+               throw invalid_argument("Message is missing the 'method' property.");
 
        for (vector<Endpoint::Ptr>::iterator i = m_Endpoints.begin(); i != m_Endpoints.end(); i++)
        {
index 6cb33299c55b014ab5b44ec06ff8a7a9c9967e7e..002125a7a35cc858f29a28bdabe1fc190a78af68 100644 (file)
@@ -168,7 +168,7 @@ int IcingaApplication::NewIcingaConfigHandler(const EventArgs& ea)
 
 int IcingaApplication::DeletedIcingaConfigHandler(const EventArgs&)
 {
-       throw Exception("Unsupported operation.");
+       throw runtime_error("Unsupported operation.");
 }
 
 void IcingaApplication::SetPrivateKeyFile(string privkey)
index 81ce236c0d4787462a2196530324cc843b441553..6386269c0af3d5ddda9eb2ed937b83c8bf9d186e 100644 (file)
@@ -132,7 +132,7 @@ int JsonRpcEndpoint::ClientClosedHandler(const EventArgs&)
 
 int JsonRpcEndpoint::ClientErrorHandler(const SocketErrorEventArgs& ea)
 {
-       cerr << "Error occured for JSON-RPC socket: Code=" << ea.Error.GetCode() << "; Message=" << ea.Error.GetMessage() << endl;
+       cerr << "Error occured for JSON-RPC socket: Message=" << ea.Exception.what() << endl;
 
        return 0;
 }
index fa6bafb01bc727131fd34aa42eb33f216103788c..72e8d2765e1e9b4c3b7d2505322e82dabbfd9676 100644 (file)
@@ -41,7 +41,7 @@ MessagePart::MessagePart(string jsonString)
        json_t *json = cJSON_Parse(jsonString.c_str());
 
        if (!json)
-               throw InvalidArgumentException("Invalid JSON string");
+               throw runtime_error("Invalid JSON string");
 
        m_Dictionary = GetDictionaryFromJson(json);
 
@@ -184,7 +184,7 @@ bool MessagePart::GetProperty(string key, MessagePart *value) const
 
        Dictionary::Ptr dictionary = dynamic_pointer_cast<Dictionary>(object);
        if (!dictionary)
-               throw InvalidCastException();
+               throw runtime_error("Object is not a dictionary.");
 
        *value = MessagePart(dictionary);
        return true;
index 10ab6686f7df126a1dd8460b54405c938418f1ef..57b7056401a161ae5b38ce63340b8c2e898f7125 100644 (file)
@@ -41,7 +41,7 @@ bool Netstring::ReadStringFromFIFO(FIFO::Ptr fifo, string *str)
 
        /* no leading zeros allowed */
        if (buffer[0] == '0' && isdigit(buffer[1]))
-               throw InvalidArgumentException("Invalid netstring (leading zero)");
+               throw invalid_argument("Invalid netstring (leading zero)");
 
        size_t len, i;
 
@@ -49,7 +49,7 @@ bool Netstring::ReadStringFromFIFO(FIFO::Ptr fifo, string *str)
        for (i = 0; i < buffer_length && isdigit(buffer[i]); i++) {
                /* length specifier must have at most 9 characters */
                if (i >= 9)
-                       throw InvalidArgumentException("Length specifier must not exceed 9 characters");
+                       throw invalid_argument("Length specifier must not exceed 9 characters");
 
                len = len * 10 + (buffer[i] - '0');
        }
@@ -60,11 +60,11 @@ bool Netstring::ReadStringFromFIFO(FIFO::Ptr fifo, string *str)
 
        /* check for the colon delimiter */
        if (buffer[i++] != ':')
-               throw InvalidArgumentException("Invalid Netstring (missing :)");
+               throw invalid_argument("Invalid Netstring (missing :)");
 
        /* check for the comma delimiter after the string */
        if (buffer[i + len] != ',')
-               throw InvalidArgumentException("Invalid Netstring (missing ,)");
+               throw invalid_argument("Invalid Netstring (missing ,)");
 
        *str = string(&buffer[i], &buffer[i + len]);