Преглед на файлове

Add dedicated message constructor to NullPointerException class

Patrick-Christopher Mattulat преди 2 години
родител
ревизия
3f6a8562d6

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

@@ -3,7 +3,7 @@
  * Company:         Lynar Studios
  * E-Mail:          webmaster@lynarstudios.com
  * Created:         2020-11-06
- * 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:
 
       NullPointerException();
+      explicit NullPointerException(::std::string _message);
       ~NullPointerException() override;
 
       [[nodiscard]] const char *what() const noexcept override;
+
+    private:
+
+      ::std::string message{};
   };
 }
 

+ 17 - 2
source/ls-std/core/exception/NullPointerException.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/NullPointerException.hpp>
 
 ls::std::core::NullPointerException::NullPointerException() = default;
 
+ls::std::core::NullPointerException::NullPointerException(::std::string _message) : message(::std::move(_message))
+{}
+
 ls::std::core::NullPointerException::~NullPointerException() = default;
 
 const char *ls::std::core::NullPointerException::what() const noexcept
 {
-  return "NullPointerException thrown - reference is null!";
+  ::std::string concatenatedMessage = "NullPointerException thrown - ";
+
+  if (this->message.empty())
+  {
+    concatenatedMessage = concatenatedMessage + "reference is null!";
+  }
+  else
+  {
+    concatenatedMessage = concatenatedMessage + this->message;
+  }
+
+  return ExceptionMessage{concatenatedMessage}.toCharacterPointer();
 }

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

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