Procházet zdrojové kódy

Add dedicated message constructor to IllegalArgumentException class

Patrick-Christopher Mattulat před 2 roky
rodič
revize
3e3da36c9c

+ 7 - 1
include/ls-std/core/exception/IllegalArgumentException.hpp

@@ -3,7 +3,7 @@
  * Company:         Lynar Studios
  * E-Mail:          webmaster@lynarstudios.com
  * Created:         2020-08-09
- * Changed:         2023-02-05
+ * Changed:         2023-02-07
  *
  * */
 
@@ -12,6 +12,7 @@
 
 #include <exception>
 #include <ls-std/os/dynamic-goal.hpp>
+#include <string>
 
 namespace ls::std::core
 {
@@ -20,9 +21,14 @@ namespace ls::std::core
     public:
 
       IllegalArgumentException();
+      explicit IllegalArgumentException(::std::string _message);
       ~IllegalArgumentException() override;
 
       [[nodiscard]] const char *what() const noexcept override;
+
+    private:
+
+      ::std::string message{};
   };
 }
 

+ 17 - 2
source/ls-std/core/exception/IllegalArgumentException.cpp

@@ -3,17 +3,32 @@
  * Company:         Lynar Studios
  * E-Mail:          webmaster@lynarstudios.com
  * Created:         2023-02-04
- * Changed:         2023-02-04
+ * Changed:         2023-02-07
  *
  * */
 
+#include <ls-std/core/exception/ExceptionMessage.hpp>
 #include <ls-std/core/exception/IllegalArgumentException.hpp>
 
 ls::std::core::IllegalArgumentException::IllegalArgumentException() = default;
 
+ls::std::core::IllegalArgumentException::IllegalArgumentException(::std::string _message) : message(::std::move(_message))
+{}
+
 ls::std::core::IllegalArgumentException::~IllegalArgumentException() = default;
 
 const char *ls::std::core::IllegalArgumentException::what() const noexcept
 {
-  return "IllegalArgumentException thrown - passed argument is not valid!";
+  ::std::string concatenatedMessage = "IllegalArgumentException thrown - ";
+
+  if (this->message.empty())
+  {
+    concatenatedMessage = concatenatedMessage + "passed argument is not valid!";
+  }
+  else
+  {
+    concatenatedMessage = concatenatedMessage + this->message;
+  }
+
+  return ExceptionMessage{concatenatedMessage}.toCharacterPointer();
 }

+ 18 - 0
test/cases/core/exception/IllegalArgumentExceptionTest.cpp

@@ -46,4 +46,22 @@ namespace
         },
         IllegalArgumentException);
   }
+
+  TEST_F(IllegalArgumentExceptionTest, constructor_dedicated_message)
+  {
+    EXPECT_THROW(
+        {
+          try
+          {
+            throw IllegalArgumentException{"value is empty"};
+          }
+          catch (const IllegalArgumentException &_exception)
+          {
+            ::std::string message = _exception.what();
+            EXPECT_STREQ("IllegalArgumentException thrown - value is empty", message.c_str());
+            throw;
+          }
+        },
+        IllegalArgumentException);
+  }
 }