From 0bfb9a46cd21797402cb2e36ba9a9a44b6b010c8 Mon Sep 17 00:00:00 2001 From: Quinten Mennen Date: Tue, 15 Apr 2025 18:52:47 +0200 Subject: [PATCH] refactored the error handling a bit --- inc/errors.h | 4 +++- src/errors.c | 20 ++++++++++++++------ src/game.c | 9 +++------ src/main.c | 3 +-- 4 files changed, 21 insertions(+), 15 deletions(-) diff --git a/inc/errors.h b/inc/errors.h index 7337d4d..c93c4ec 100644 --- a/inc/errors.h +++ b/inc/errors.h @@ -15,6 +15,8 @@ # include "cub3d.h" -void game_error(t_game *game, const char *msg, int mlx_error); + +const char *last_error(); +void game_error(t_game *game, const char *msg); #endif diff --git a/src/errors.c b/src/errors.c index b7669c4..3b69f8d 100644 --- a/src/errors.c +++ b/src/errors.c @@ -13,14 +13,22 @@ #include "MLX42.h" #include "cub3d.h" -void game_error(t_game *game, const char *msg, int mlx_error) +const char *last_error() { - if (mlx_error) - printf(RED"%s\n"RESET, mlx_strerror(mlx_errno)); - else if (msg == NULL) - printf(RED"%s\n"RESET, strerror(errno)); + if (mlx_errno > 0) + return (mlx_strerror(mlx_errno)); + else if (errno > 0) + return (strerror(errno)); + else + return (NULL); +} + +void game_error(t_game *game, const char *msg) +{ + const char *last_err = last_error(); + if (msg == NULL && last_err) + printf(RED"%s\n"RESET, last_err); else printf(RED"%s\n"RESET, msg); game_terminate(game); - exit(FAILURE); } diff --git a/src/game.c b/src/game.c index 687a4fb..88beed1 100644 --- a/src/game.c +++ b/src/game.c @@ -10,16 +10,13 @@ /* */ /* ************************************************************************** */ -#include "game.h" +#include "cub3d.h" int game_create(t_game **game) { *game = malloc(sizeof(t_game)); if (!game) - { - printf("malloc: game failed\n"); - exit(FAILURE); - } + return (FAILURE); (*game)->player = NULL; (*game)->map = NULL; (*game)->screen = screen_create(); @@ -53,5 +50,5 @@ void game_terminate(t_game *game) if (game->map) free(game->map); free(game); - exit(EXIT_SUCCESS); + exit(EXIT_SUCCESS); //TODO: Make this variable on the last error } diff --git a/src/main.c b/src/main.c index ea718b0..f4b66f9 100644 --- a/src/main.c +++ b/src/main.c @@ -10,7 +10,6 @@ /* */ /* ************************************************************************** */ -#include "MLX42.h" # include "cub3d.h" int main(void) @@ -19,7 +18,7 @@ int main(void) game = NULL; if (! game_create(&game)){ - game_error(game, "Failed to create game", 0); + game_error(game, NULL); return (EXIT_FAILURE); } screen_center(game->screen);