meaningful_life
meaningful life
meaningful_life
전체 방문자
오늘
어제
  • 분류 전체보기 (28)
    • Programming (28)
      • Backend (25)
      • Machine Learning (1)
      • Infrastructure (2)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

  • 자바
  • error
  • Kubernetes
  • Spring
  • 백준
  • Database
  • docker
  • 머신러닝
  • ufw
  • ubuntu
  • kubectl
  • git
  • linux
  • 자바의신
  • python
  • install
  • java
  • flask
  • stringbuilder
  • 쿠버네티스

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
meaningful_life

meaningful life

6.Flask error, exception general handling
Programming/Backend

6.Flask error, exception general handling

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

'Programming > Backend' 카테고리의 다른 글

7.Flask 회원가입, 로그인 암호화 및 JWT + Redis  (2) 2022.06.08
5.Flask sqlalchemy - get, create  (0) 2022.05.29
4.Flask restx 적용 + Swagger  (0) 2022.05.29
3.Flask Database 연결 + Config 설정  (0) 2022.04.30
2.Flask MVC 패턴 환경 구축과 Blueprint  (0) 2022.04.22
    'Programming/Backend' 카테고리의 다른 글
    • 7.Flask 회원가입, 로그인 암호화 및 JWT + Redis
    • 5.Flask sqlalchemy - get, create
    • 4.Flask restx 적용 + Swagger
    • 3.Flask Database 연결 + Config 설정
    meaningful_life
    meaningful_life
    하루하루가 의미 있고 가치 있는 삶이 될 수 있길. 그리고 나의 추억과 각종 지식의 기록과 이를 공유함으로써 다른 사람에게도 도움이 되길...

    티스토리툴바