From cbebf0cc1e76749cdcb1b57fdc536a3c238c30e4 Mon Sep 17 00:00:00 2001 From: Marcel Pohland Date: Wed, 16 Oct 2024 13:33:07 +0200 Subject: [PATCH] better error handling and remove traceback logs --- prom2teams/app/versions/v2/__init__.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/prom2teams/app/versions/v2/__init__.py b/prom2teams/app/versions/v2/__init__.py index 72c230d..b0dab9a 100644 --- a/prom2teams/app/versions/v2/__init__.py +++ b/prom2teams/app/versions/v2/__init__.py @@ -1,5 +1,6 @@ import logging from flask_restx import Api +from werkzeug.exceptions import HTTPException log = logging.getLogger(__name__) @@ -9,6 +10,26 @@ @api_v2.errorhandler def default_error_handler(e): + # Define a default error message at the start msg = 'An unhandled exception occurred.' - log.exception(msg + e) - return {'message': msg}, 500 + + # Log the full stack trace for debugging + # log.exception(f"{msg}: {str(e)}\n{traceback.format_exc()}") + + # Customize the response based on the type of exception + if isinstance(e, HTTPException): + # Set a specific message for HTTPException + msg = e.description + # Return a dictionary for the HTTPException's description and code + return {'message': msg}, e.code + elif isinstance(e, ValueError): + # For ValueError, set a specific message and return a 400 Bad Request code + msg = 'Invalid value provided.' + return {'message': msg}, 400 + elif isinstance(e, KeyError): + # For KeyError, set a specific message and return a 400 Bad Request code + msg = 'Missing required data.' + return {'message': msg}, 400 + else: + # Generic response for other unhandled exceptions + return {'message': msg}, 500 \ No newline at end of file