An error object with error information in it.
It supports multiple layers of error messages, custom contents, custom function and printable.
This would be helpful to convert the error into some actions and logging the error message.
ErrorBaseObj
.ToReadableString
to convert the error object to a readable string.SelfCopy
to copy itself.CustomError
to simplify the usage.CreateError
helper function to create some special error type, for example: nullptr
.CreateErrorWrap
helper function to create some special error.class CustomErrorObj : public ErrorBaseObj { public: explicit ErrorObj(const std::string& error_message) : error_message_(error_message) {} explicit ErrorObj(std::string&& error_message) : error_message_(std::move(error_message)) {} virtual ~ErrorObj() = default; hwsec_foundation::error::ErrorBase SelfCopy() const { return std::make_unique<ErrorObj>(error_message_); } std::string ToReadableString() const { return error_message_; } protected: ErrorObj(ErrorObj&&) = default; private: const std::string error_message_; }; using CustomError = std::unique_ptr<CustomErrorObj>; template <typename ErrorType, typename T, typename std::enable_if< std::is_same<ErrorType, CustomError>::value>::type* = nullptr, decltype(CustomErrorObj( std::forward<T>(std::declval<T&&>())))* = nullptr> CustomError CreateError(T&& error_msg) { if (error_msg == "") { return nullptr; } return std::make_unique<CustomError>(std::forward<T>(error_msg)); }
auto
? Similar to the style of unique_ptr.auto
when the error is created by CreateError<>
or CreateErrorWrap<>
if (auto err = CreateError<TPM1Error>(0x99)) { /* Do some error handlings... */ }
if (TPM1Error err = SomeMagicFunction()) { /* Do some error handlings... */ }
if
expression:if (TPM1Error err = SomeMagicFunction()) { /* Do some error handlings... */ }
if (SomeMagicFunction()) { /* Don’t do this. */ }Please use:
if (SomeMagicFunction() != nullptr) { /* This it better */ /* But should think about why we need to drop the extra error information in this case. */ /* For example: Should we log more messages in this case? */ }