Backend/FastAPI

FastAPI에서 handling error - exception 정의 및 적용

amelia-suyeon 2023. 6. 26. 18:26

필자는 error를 처리하는데 있어서, HTTPStatus library를 사용했음! 

 

여기서, Error Handling 이란?

- 웹 서버를 안정적으로 운영하기 위해 반드시 필요한 주제

- 서버에서 error가 발생했을 때, 어떤 error(즉 status code) 및 설명이 꼭 필요

☞ 따라서 여러 라이브러리 및 도구를 활용하여 Error log 수집 및 관리의 중요성! 

 

아래와 같이 공식 문서를 꼭 읽어보는 것을 추천!

 

공식 문서 : https://fastapi.tiangolo.com/tutorial/handling-errors/

 

Handling Errors - FastAPI

Handling Errors There are many situations in where you need to notify an error to a client that is using your API. This client could be a browser with a frontend, a code from someone else, an IoT device, etc. You could need to tell the client that: The cli

fastapi.tiangolo.com

 

먼저, 더 많은 종류가 존재하지만, 필자는 2가지를 주로 이용하였다. 

 

1. JSONResponse를 사용한 custom excepetion handler

2. 그 외 httpstatus를 이용하여 class 화

 

먼저 1번 구현 예제) 

# 1 
 
class CustomException(Exception):
    def __init__(self,name: str):
        self.name = name
 
 
 
@app.exception_handler(CustomException)
    async def exception_handler_v2(request: Request, exc: CustomException):
        return JSONResponse(
            status_code= 417,
            content={"error_code": 417, "message": f"{exc.name}  request body not matched column "},
        )
 
 
 
@app.get('/something/{name}')
def get_something(name:str):
    if name == 'sugar':
        raise CustomException(name=name)
    return {'data_name': name}
 
 

 

# 1을 보면, 예외 처리를 원하는 대로 만들어서 처리하고 싶을 때

-> @app.exception_handler() 구문을 통해 처리 할 수 있다!

그 외,  error_code, message, 등등 커스텀 하여 사용 가능함

 

 

 

2번 구현 예제)

# exception.py
 
 
from http import HTTPStatus

""" 공통 error 정의 """
 
class BasicException(Exception):
    code = HTTPStatus.BAD_GATEWAY
    error_code = HTTPStatus.BAD_GATEWAY
    message = HTTPStatus.BAD_GATEWAY.description

    def __init__(self, message=None):
        if message:
            self.message = message


class BadRequestException(BasicException):
    code = HTTPStatus.BAD_REQUEST
    error_code = HTTPStatus.BAD_REQUEST
    message = HTTPStatus.BAD_REQUEST.description
import exception
 
 
def init_listener_v2(_app: FastAPI) -> None:
    @app.exception_handler(exception.BasicException)
    async def exception_handler(request: Request, exc: exception.BasicException):
        return JSONResponse(
            status_code=exc.code,
            content={"error_code": exc.error_code, "message": exc.message},
        )
 
 

 

 

1. exception.py 에 error들을 정의한다(가장 많이 발생하는 400, 404, 422, 500) 

2. exception.py를 참조하여, 핸들러 초기값에 사용함 

3. 다른 필요한 error들을 class 에 추가하여 사용 가능함