From 6ad2bbc45b33c0a40d22af391e02c1684c988657 Mon Sep 17 00:00:00 2001 From: nikhilleo10 Date: Wed, 22 Nov 2023 18:25:56 +0530 Subject: [PATCH] Add slack notifications for error messages --- .env | 3 ++- .env.example | 3 +++ .github/workflows/cd-dev.yml | 2 +- .github/workflows/cd-prod.yml | 2 +- app.py | 15 +++++++++++++++ utils/slack_notification_utils.py | 27 +++++++++++++++++++++++++++ 6 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 utils/slack_notification_utils.py diff --git a/.env b/.env index 4db49ff..f789355 100644 --- a/.env +++ b/.env @@ -6,4 +6,5 @@ DB_NAME=fastapi OPENAI_API_KEY_GPT4= OPENAI_API_KEY_WEDNESDAY= YOUR_SECRET_KEY=my_super_secret_key_here -# REDIS_URL=http://localhost:6379 \ No newline at end of file +# REDIS_URL=http://localhost:6379 +SLACK_WEBHOOK_URL=https://hooks.slack.com/services/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 \ No newline at end of file diff --git a/.env.example b/.env.example index 03dfa4b..c574ab1 100644 --- a/.env.example +++ b/.env.example @@ -5,3 +5,6 @@ DB_PORT= DB_NAME= OPENAI_API_KEY_GPT4= OPENAI_API_KEY_WEDNESDAY= +YOUR_SECRET_KEY= +REDIS_URL= +SLACK_WEBHOOK_URL= \ No newline at end of file diff --git a/.github/workflows/cd-dev.yml b/.github/workflows/cd-dev.yml index a19092c..7bdf9b0 100644 --- a/.github/workflows/cd-dev.yml +++ b/.github/workflows/cd-dev.yml @@ -39,4 +39,4 @@ jobs: - name: Deploy ECS run: | - ./scripts/update-ecs.sh ${{ env.ENVIRONMENT_NAME }} + ./scripts/update-ecs.sh develop diff --git a/.github/workflows/cd-prod.yml b/.github/workflows/cd-prod.yml index fff440c..49555fe 100644 --- a/.github/workflows/cd-prod.yml +++ b/.github/workflows/cd-prod.yml @@ -39,4 +39,4 @@ jobs: - name: Deploy ECS run: | - ./scripts/update-ecs.sh ${{ env.ENVIRONMENT_NAME }} + ./scripts/update-ecs.sh develop diff --git a/app.py b/app.py index 45adba0..7640d81 100644 --- a/app.py +++ b/app.py @@ -12,6 +12,8 @@ from middlewares.rate_limiter_middleware import RateLimitMiddleware from pybreaker import CircuitBreakerError from dependencies import circuit_breaker +from utils.slack_notification_utils import send_slack_message +import traceback # Initializing the swagger docs app = FastAPI( @@ -39,6 +41,7 @@ # Default API route @app.get("/") async def read_main(): + 1/0 return {"response": "service up and running..!"} @@ -81,6 +84,18 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE async def http_exception_handler(request: Request, exc: HTTPException): return JSONResponse(status_code=exc.status_code, content={"success": False, "message": exc.detail}) +@app.exception_handler(Exception) +async def http_exception_handler(request: Request, exc: Exception): + error_message = f'Error: {str(exc)}' + # Include the traceback in the response for debugging purposes + traceback_str = traceback.format_exc() + send_slack_message({ "text": f'```{traceback_str}```', "request_url": str(request.url), "request_method": str(request.method)}) + + return JSONResponse( + status_code=500, + content={"success": False, "message": error_message } + ) + @app.get("/{path:path}") async def catch_all(path: str): diff --git a/utils/slack_notification_utils.py b/utils/slack_notification_utils.py new file mode 100644 index 0000000..0f02240 --- /dev/null +++ b/utils/slack_notification_utils.py @@ -0,0 +1,27 @@ +import os +import requests +import json +from dotenv import load_dotenv +from fastapi import HTTPException + +load_dotenv() + +def send_slack_message(payload): + """Send a Slack message to a channel via a webhook. + + Args: + payload (dict): Dictionary containing Slack message, i.e. {"text": "This is a test"} + Returns: + HTTP response code, i.e., + """ + webhook_url = os.environ.get('SLACK_WEBHOOK_URL') # Use get to avoid KeyError + + if not webhook_url: + raise HTTPException(status_code=400, detail="Slack URL not configured.") + + headers = { + 'Content-Type': 'application/json', # Specify the content type + } + + response = requests.post(webhook_url, headers=headers, data=json.dumps(payload)) + return response \ No newline at end of file