Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Template azure function #3

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Custom Exceptions and Handlers
  • Loading branch information
lpinon committed Jun 27, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit e29b8fbe683d44a374827a0d99ec45b0f4b3a46c
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@
- [X] Database Configuration
- [ ] ASYNC Database Configuration
- [X] Swagger Configuration
- [ ] JWT / Keycloak Integration
- [X] JWT / Keycloak Integration
- [X] CORS Configuration
- [ ] Global Exception Management
- [X] Global Exception Management
- [ ] DB Entity Generation
- [ ] Code generation using Templates
- [X] Log to files integration
4 changes: 4 additions & 0 deletions app/core/Configuration.py
Original file line number Diff line number Diff line change
@@ -10,6 +10,8 @@


# Configuration Objects Definitions
from app.core.exception_handlers import init_exception_handlers


class GlobalSettings(BaseSettings):
app_name: str = "My Awesome API"
@@ -131,4 +133,6 @@ def get_api():
# Include all Routers
from app.controllers import api_router
api.include_router(api_router)
# Init exception Handlers
init_exception_handlers(api)
return api
28 changes: 28 additions & 0 deletions app/core/exception_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import logging

from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import PlainTextResponse

from app.exceptions.http import DevonHttpException
from app.exceptions.runtime import DevonCustomException

logger = logging.getLogger(__name__)


def init_exception_handlers(api: FastAPI):
# Custom HTTP Exception Handler
@api.exception_handler(DevonHttpException)
async def http_exception_handler(request: Request, exc):
logger.error(str(request.url) + " - Path params: " + str(request.path_params) +
" - Query Params: " + str(request.query_params))
logger.exception(exc.detail)
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

# Custom Runtime Exception Handler
@api.exception_handler(DevonCustomException)
async def runtime_exception_handler(request: Request, exc: DevonCustomException):
logger.error(str(request.url) + " - Path params: " + str(request.path_params) +
" - Query Params: " + str(request.query_params))
logger.exception(exc.detail)
return PlainTextResponse(str(exc.detail), status_code=500)
Empty file added app/exceptions/__init__.py
Empty file.
27 changes: 27 additions & 0 deletions app/exceptions/http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import Any, Optional, Dict

from fastapi import HTTPException


##################################
# Base HTTP Exception
##################################


class DevonHttpException(HTTPException):
def __init__(self, status_code: int, detail: str = None, headers: Optional[Dict[str, Any]] = None):
super().__init__(status_code=status_code, detail=detail, headers=headers)


##################################
# Custom HTTP Exceptions
##################################

class NotFoundException(DevonHttpException):
def __init__(self, detail: str = "Not found", headers: Optional[Dict[str, Any]] = None):
super().__init__(status_code=404, detail=detail, headers=headers)


class DevonHttpExceptionWithCustomHeader(DevonHttpException):
def __init__(self):
super().__init__(status_code=403, detail="Custom Header Exception", headers={"X-Error": "There goes my error"})
17 changes: 17 additions & 0 deletions app/exceptions/runtime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
##################################
# Base Runtime Exception
##################################

class DevonCustomException(RuntimeError):
def __init__(self, detail: str = None):
super().__init__()
self.detail = detail


##################################
# Custom Runtime Exceptions
##################################

class UnexpectedStatusException(DevonCustomException):
def __init__(self):
super().__init__("Unexpected status found")
5 changes: 4 additions & 1 deletion app/services/user.py
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@

from fastapi import Depends

from app.exceptions.http import NotFoundException
from app.models import User
from app.repositories.user import get_user_repository, UserRepository

@@ -11,4 +12,6 @@ def __init__(self, repository: UserRepository = Depends(get_user_repository)):
self.user_repo = repository

async def get_user_by_email(self, email: str) -> Optional[User]:
return await self.user_repo.get_by_email(email=email)
user = await self.user_repo.get_by_email(email=email)
if user is None:
raise NotFoundException(detail="User not found")
2 changes: 2 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -6,6 +6,8 @@
from app.core.database import init_db_entities

# Init APP with Configuration
from app.exceptions.http import NotFoundException
from app.exceptions.runtime import UnexpectedStatusException
from app.services.user import UserService

api = get_api()