Skip to content

Commit

Permalink
Add slack notifications for error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilleo10 committed Nov 22, 2023
1 parent 3f8fef9 commit 6ad2bbc
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -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
# REDIS_URL=http://localhost:6379
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ DB_PORT=
DB_NAME=
OPENAI_API_KEY_GPT4=
OPENAI_API_KEY_WEDNESDAY=
YOUR_SECRET_KEY=
REDIS_URL=
SLACK_WEBHOOK_URL=
2 changes: 1 addition & 1 deletion .github/workflows/cd-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ jobs:

- name: Deploy ECS
run: |
./scripts/update-ecs.sh ${{ env.ENVIRONMENT_NAME }}
./scripts/update-ecs.sh develop
2 changes: 1 addition & 1 deletion .github/workflows/cd-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ jobs:

- name: Deploy ECS
run: |
./scripts/update-ecs.sh ${{ env.ENVIRONMENT_NAME }}
./scripts/update-ecs.sh develop
15 changes: 15 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -39,6 +41,7 @@
# Default API route
@app.get("/")
async def read_main():
1/0
return {"response": "service up and running..!"}


Expand Down Expand Up @@ -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):
Expand Down
27 changes: 27 additions & 0 deletions utils/slack_notification_utils.py
Original file line number Diff line number Diff line change
@@ -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., <Response [503]>
"""
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

0 comments on commit 6ad2bbc

Please sign in to comment.