First time here? Checkout the FAQ!
x
0 votes
ago by (150 points)
What is the preferred way to output an error message and stop openCARP when an error condition makes further execution impossible or useless? I see several approaches being taken in the code, but no convenient function that combines a printf() with an exit() or abort().

1 Answer

0 votes
ago by (960 points)
selected ago by
 
Best answer

Hey Mark,

I think the common approach in the code would be to use the combination of 

log_msg(out, level, flag, fmt)

exit(EXIT_FAILURE)

log_msg() safely prints an error/warning message either to a file or command line depending on the parameters used. Theoretically, the documentation states that using level  as MAX_LOG_LEVEL (=5) means catastrophic failure. At the moment, the call to exit() is not included in the function. Maybe this could be done to simplify the process.

ago by (150 points)
Thanks! I'll stick to this convention when I propose changes in the code.

Indeed I would find it convenient to do this in one function call so that it is easy to catch unforeseen cases (in one line instead of four), like in

   else ERROR("this cannot happen: foo=%d", foo)

but I would find it counterintuitive to call log_msg(0, 5, ...) in such a case. I would propose something like this C99 code:

#define ERROR(...) err_exit(__LINE__, __FILE__, __VA_ARGS__)
void err_exit(const int line, const char *file, const char *fmt, ...)
{
  va_list argp;

  fprintf(stderr, "\nERROR: ");
  va_start(argp, fmt);
  vfprintf(stderr, fmt, argp);
  va_end(argp);
  fprintf(stderr, "\n  Line %d of %s,", line, file);
  fprintf(stderr, "\n  errno = %d (%s)\n\n ==> ", errno, strerror(errno));
  fflush(stdout);
  fflush(stderr);
  abort();        // get a core dump to facilitate debugging
}
 

The line and file are helpful to find out where in the code a particular error message is coming from, and makes it less problematic if you have lots of identical error messages.
Welcome to openCARP Q&A. Ask questions and receive answers from other members of the community. For best support, please use appropriate TAGS!
architecture, carputils, documentation, experiments, installation-containers-packages, limpet, slimfem, website, governance
...