How to enforce project-wide unique ids/error codes for easily finding the origin of the error in source code?

对着背影说爱祢 提交于 2020-01-04 17:00:26

问题


It is convenient to use unique error codes that the user will see on an error. This will make it easier to locate the origin of the error for the developer (just do a search in the source code for the error code), thus saving time.

Example:

void f()
{
  std::cout << "UNIQUE001 " << "Error : The query failed" << std::endl;
}

void g()
{
  f();
}

int main()
{
  g();
  return 0;
}

In the example, the user reports the error ("UNIQUE001 Error : The query failed"). The developer just does a project-wide search on "UNIQUE001", and immediately finds where the error was thrown. (A file with line number does not suffice, as the code might have changed in the meantime).

So, to the question : Is there a way to enforce the uniqueness of the error code strings at compile-time (ideally, with either preprocessor macros or TMP) or at run-time (e.g. in a unit test)?

UPDATE

My best attempt so far has been to make a struct with a macro, that creates a type with a value string equal to the type name and error code. This works and gives a compile time error for duplicate types, but structs can't be declared everywhere (e.g. in an expression)

#define generateerrorcode(code) \
struct code \
{ \
  static const char* value = #code \
}; \

I'd like to be able to use unique-checking functionality like this, if possible:

void some_function()
{
  std::cout << check_unique("UNIQUE001") << "Error : The query failed" << std::endl;
}

回答1:


If you want to be 100% sure, you can use GUID and one of many millions of generators that are out there.




回答2:


You say:

(A file with line number does not suffice, as the code might have changed in the meantime).

But what if you will not wtire it your self but compiler will? i.e __FILE__, __LINE__, __FUNCTION__. See: __FILE__, __LINE__, and __FUNCTION__ usage in C++

However, it'll fail if code was changed after error but before you'll fix it. (But you may see edit history)



来源:https://stackoverflow.com/questions/14176128/how-to-enforce-project-wide-unique-ids-error-codes-for-easily-finding-the-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!