From c0bdc6ca17b883911b1a4bff0ee947ddd40823e8 Mon Sep 17 00:00:00 2001 From: Quinn Date: Tue, 4 Mar 2025 14:29:58 +0100 Subject: [PATCH] add better error handling to include line and file in error messages --- src/error.c | 14 +++++++++----- src/error.h | 16 ++++++++++------ 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/error.c b/src/error.c index effa67f..bb6f674 100644 --- a/src/error.c +++ b/src/error.c @@ -49,11 +49,15 @@ void warn(char const* fmt, ...) { (void)fprintf(stderr, "\033[93mW: %s\033[0m\n", buf); } -noreturn void error(gamestatus error_code, char const* fmt, ...) { - char buf[PRINT_BUFFER_SIZE] = {0}; - write_args(buf, fmt); - (void)fprintf(stderr, "\033[91mE: %s\033[0m\n", buf); - SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "something went wrong! :O", buf, NULL); +noreturn void i_error(gamestatus error_code, uint32_t ln, char const* fname, char const* fmt, ...) { + char buf1[PRINT_BUFFER_SIZE] = {0}; + write_args(buf1, fmt); + + char buf2[PRINT_BUFFER_SIZE * 2] = {0}; + sprintf(buf2, "%s\n at %s:%u", buf1, fname, ln); + + (void)fprintf(stderr, "\033[91mE: %s\033[0m\n", buf2); + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "something went wrong! :O", buf2, NULL); // set status, but exit immediately, as code is not allowed to execute beyond this point set_gamestatus(error_code); diff --git a/src/error.h b/src/error.h index f475d9d..d6c1cef 100644 --- a/src/error.h +++ b/src/error.h @@ -1,6 +1,7 @@ #pragma once #include +#include /* defines statuses in the 0..127, any higher/negative values are POSIX-reserved. * The max value (or -1) shall mean the application is running, anything else shall mean an exit code of some kind */ @@ -27,9 +28,12 @@ enum { }; typedef int8_t gamestatus; -void set_gamestatus(gamestatus); // sets the current status of the game -gamestatus get_gamestatus(void); // gets the current status of the game -void debug(char const*, ...); // prints a debug message to stdout if the DEBUG environment variable is set, otherwise the call is ignored. -void info(char const*, ...); // prints an info message to stdout -void warn(char const*, ...); // prints a warning message to stderr -void error(gamestatus, char const*, ...); // prints an error message to stderr before exiting +void set_gamestatus(gamestatus); // sets the current status of the game +gamestatus get_gamestatus(void); // gets the current status of the game +void debug(char const*, ...); // prints a debug message to stdout if the DEBUG environment variable is set, otherwise the call is ignored. +void info(char const*, ...); // prints an info message to stdout +void warn(char const*, ...); // prints a warning message to stderr + +// prints an error message to stderr before exiting +#define error(status, fmt, ...) i_error(status, __LINE__, __FILE__, fmt, __VA_ARGS__) +noreturn void i_error(gamestatus, uint32_t, char const*, char const*, ...);