-
FastAPI에서 handling error - exception 정의 및 적용Backend/FastAPI 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번 구현 예제)
# 1class 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.pyfrom http import HTTPStatus
""" 공통 error 정의 """class BasicException(Exception):code = HTTPStatus.BAD_GATEWAYerror_code = HTTPStatus.BAD_GATEWAYmessage = HTTPStatus.BAD_GATEWAY.description
def __init__(self, message=None):if message:self.message = message
class BadRequestException(BasicException):code = HTTPStatus.BAD_REQUESTerror_code = HTTPStatus.BAD_REQUESTmessage = HTTPStatus.BAD_REQUEST.descriptionimport exceptiondef 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 에 추가하여 사용 가능함
'Backend > FastAPI' 카테고리의 다른 글
FastAPI 로 router 구현하기 (2) 2023.06.26 FastAPI - main.py 구성하기 (0) 2023.06.26 Poetry를 이용하여 FastAPI 구현하기 - 3 (0) 2023.06.26 Poetry를 이용하여 FastAPI 구현하기 - 2 (0) 2023.06.26 Poetry를 이용하여 FastAPI 구현하기 - 1 (0) 2023.06.26