0
votes

I was trying to build my own error handler that throws errors depending on the some error numbers that i have implimented in an enum class errorNo{}. I also wanted to include the source function using __PRETTY_FUNCTION__. The error handler looks like this (less complicated version ... with std::string ... without errorNo from the enum):

void errorHandler(std::string message, int errorCode){
switch (errorCode){
default:
throw std::runntime_error(message); } }

Then call it like:

errorHandler(std::string("Error in: ")+__PRETTY_FUNCTION__, 0);

Is there a way for the errorhandler to automatically get the function name in which it was called without any explicit declaration? I tried:

void errorHandler(std::string message, int errorCode , const char* functionName = __PRETTY_FUNCTION__){

throw std::runntime_error(message + " in " + functionName)

}

I get a warning that __PRETTY_FUNCTION__ is only allowed in function and even after i get an ouput, i get the 'error in top level'.

1

1 Answers

0
votes

You can store the __PRETTY_FUNCTION__ in a std::string in that particular function and then pass that string to errorHandler function.

Something like this:

void foo()
{
    std::string message, funcName;
    message = "Error";
    funcName = __PRETTY_FUNCTION__;
    errorHandler(message, 0 , funcName);
}

See live demo here.