Coding tip; pretty-printing enum values.

I've been in computers too long, whenever someone talks to me about error codes I think about the very old MacOs releases, or even longer ago the Amiga crash codes.
But I'm afraid you see them still, a dialog giving a very helpful "sorry, error 1234 happened".

Now, anyone that is a coder knows how difficult it is to handle each and every error with a properly written error message. Preferrably one that actually makes sense to the user. And realistically speaking this tends not to happen. But before now the effect was typically to have useless messages like the above, or use some hacks that might get out of date on refactorings.
If you look at Qt there are several classes that have an error state; QNetworkReply is one of them. This error state is an enum and in C++ enums really are just integers.
In Qt we allow an enum to be more than just a set of integers using the Q_ENUMS macro. The direct benefit for you is that you can use introspection (/reflection) to get the string value of an enum.

So, no more excuses for just printing an integer error message, you can at least print the more readable enum value. Which means that technical people that don't have the API docs for Qt handy can still figure out what went wrong.

Here is the code to do this;

QNetworkReply::NetworkError error;
error = fetchStuff();
if (error != QNetworkReply::NoError) {
QString errorValue;
QMetaObject meta = QNetworkReply::staticMetaObject;
for (int i=0; i < meta.enumeratorCount(); ++i) {
QMetaEnum m = meta.enumerator(i);
if (m.name() == QLatin1String("NetworkError")) {
errorValue = QLatin1String(m.valueToKey(error));
break;
}
}
QMessageBox box(QMessageBox::Information, "Failed to fetch",
"Fetching stuff failed with error '%1`").arg(errorValue),
QMessageBox::Ok);
box.exec();
return 1;
}

In Qt every class that has the Q_OBJECT macro will automatically have a static member "staticMetaObject" of the type QMetaObject. You can then find all sorts of cool things like the properties, signals, slots and indeed enums.

Happy hacking :)


Blog Topics:

Comments