Utility class for temporary error information storage?
I have been writing a light-weight framework to wrap the Windows API for personal projects and some fun. What I think is a good design method is that each class in the framework manages its own error information whenever something goes wrong. I have a simple error class like so:
class Error
{
public:
struct ErrorData
{
DWORD sysErrCode;
tstring sysErrStr;
SYSTEMTIME localTime;
tstring errMs开发者_如何学编程g;
tstring funcCall;
tstring parentClass;
};
void getErrorData(ErrorData *pErrorData);
Error(const tstring parentClass);
void setErrorData(const tstring errMsg, const tstring funcCall, const bool getSysErr = false);
private:
ErrorData errorData;
void getSystemError(DWORD &sysErrCode, tstring &sysErrStr);
};
What I'm stuck on is how to incorporate this class into the other classes. Inheritance sounds wrong because a dialog class is not an Error class. Composition sounds better, a dialog class can have an Error class. But then I'm stuck writing a getter function for every class to retrieve the Error class's information. Although that would only take a short time to write, there has got to be a better design method. I would rather not have to copy and paste those functions in every class either.
Any ideas would be appreciated! Thank you.
Have you considered using exceptions and throw
ing your ErrorData
class instead? That seems better than either inheritance or composition.
It almost looks like getSystemError
should be a namespace free-function instead of a member (it looks like everything it needs is passed into its parameters).
First of all, I have to recommend using Exceptions for error management. You could have one exception type that is used unilaterally in your application, or you could create a hierarchy of exception types that are specialized for specific classes.
If you don't want to go down that route, you can still get away from having to implement a special getter function for errors in each of your classes, you can use inheritance pretty painlessly. Just make a base class that all objects with error management inherit from, and implement a getter once in the base class:
class ErrorManager
{
const Error& getError();
void setError( Error& err ); // Or however you would actually set the error
}
class Widget : public ErrorManager
{
// Implementation details
}
Widget w;
w.getError()
While you think that inheritance seems wrong, it is really quite appropriate. You are correct that a Dialog is not an Error. However, it does have-a Error, and you can manage interaction with that error by using inheritance. Therefore, your dialog is-a ErrorManager because it uses a common framework for managing its errors.
Good Luck!
精彩评论