Software Backend/Python & Django & flask

6.Flask error, exception general handling

light_meal 2022. 5. 29. 22:34
728x90

6.Flask error, exception general handling

Web Application 전역에서 발생하는 Error에 대한 Exception을 임의로 작성하여 사용해보겠습니다.

https://github.com/kschoi93/flask-example

 

init에 Error handler 등록

# general error handler
    from .common.errors import error_handle
    error_handle(app)

 

toy.common.errors.py 등록

from .exceptions import *

def error_handle(app):
    @app.errorhandler(CustomException)
    def example_error(e):
        return e.to_json(), e.to_json()['status']

 

toy.common.exceptions.py 등록

class CustomException(Exception):
    status_code = 601
    message = '요청에 실패 했습니다'

    def __init__(self):
        super().__init__()

    def to_json(self):
        response = dict(status=self.status_code, message=self.message)
        return response

 

toy.daos.example_dao.py

Get ID 하였을 때 데이터가 없어 None일 경우 에러가 발생하도록 합니다.

from toy import db

from toy.models.example_models import ExampleUser
from toy.common.exceptions import CustomException

class ExampleDAO(object):
    def __init__(self):
        pass

    def get(self, name: str) -> str:
        user = ExampleUser.query.filter_by(name=name).first()
        if user is None:
            raise CustomException()
        return user.name

    def create(self, name: str):
        user = ExampleUser(name=name)
        db.session.add(user)
        db.session.commit()

 

테스트 결과

728x90