FastAPI Raise HTTP Exception(사용자 지정) - 24

2022. 12. 24. 14:26·Develop/FastAPI
728x90
SMALL
HTTP 에러를 사용자에 맞게 커스텀이 가능하다.(음수가 조건에 들어왔을 때 에러가 나오게 하는 게 목표)

1. import JSONResponse, Request

from fastapi import FastAPI, HTTPException, Request
from starlette.responses import JSONResponse

 

2. Exception을 상속하는 클래스 생성

class NegativeNumberException(Exception):
    def __init__(self, books_to_return: int):
        self.books_to_return = books_to_return

 

3. @app.exception_handler() 데코레이션을 사용하여 handler를 등록

@app.exception_handler(NegativeNumberException)
async def negative_number_exception_handler(request: Request, exception: NegativeNumberException):

    return JSONResponse(
        status_code=418,
        content={"message":f"Hey, why do you want {exception.books_to_return}"
                           f"books? you need to read more!"}
  • 예외를 요청하는 Request
  • exception이라는 매개변수를 NegativeNumberException 클래스라고 정의(클래스의 값들을 쓸 수 있음)
  • JSON응답을 반환(code 418 에러와 같이 출력할 메시지 content를 정의)
code 418: 서버는 해당 응답을 회신 할 수 없다는 오류코드
즉, 조건에 맞지 않는 요청을 했기 때문에 나는 오류

 

4. GET 요청 함수에 조건값 추가

@app.get("/")
async def read_all_books(books_to_return: Optional[int] = None):

    if books_to_return and books_to_return < 0:
        raise NegativeNumberException(books_to_return=books_to_return)

    if len(BOOKS) < 1:
        create_books_no_api()

    if books_to_return and len(BOOKS) >= books_to_return > 0:
        i = 1
        new_books = []
        while i <= books_to_return:
            new_books.append(BOOKS[i - 1])
            i += 1
        return new_books
    return BOOKS
  • books_to_return이 존재하고 0보다 작을 때 handler에 등록한 NegativeNumberException 클래스에 요청 들어온 값을 담는다.
  • handler가 반응을 하고 418 code와 content를 return 한다.

 

5. Swagger 확인

  • 1을 넣었을 땐 200 code로 값을 잘 가져온 것을 볼 수 있고 -1을 넣었을 때 사전 오류로 정의한 것이 잘 노출되고 있다.

728x90
SMALL
저작자표시 비영리 변경금지 (새창열림)

'Develop > FastAPI' 카테고리의 다른 글

FastAPI Status Code Response - 26  (0) 2022.12.24
FastAPI Response Model - 25  (0) 2022.12.24
FastAPI Raise HTTP Exception - 23  (0) 2022.12.24
FastAPI Delete Request - 22  (0) 2022.12.23
FastAPI Put Request - 21  (2) 2022.12.23
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI Status Code Response - 26
  • FastAPI Response Model - 25
  • FastAPI Raise HTTP Exception - 23
  • FastAPI Delete Request - 22
동석해요
동석해요
공부하고 싶은게 많은, 사소한 IT 지식들 공유
    250x250
  • 동석해요
    개발로 자기계발
    동석해요
  • 전체
    오늘
    어제
    • 분류 전체보기 (226)
      • Develop (126)
        • 기초지식 (12)
        • FastAPI (102)
        • Django (11)
      • Database & Data (62)
        • 기초지식 (16)
        • MySQL (29)
        • PostgreSQL (8)
        • 데이터 분석 (9)
      • 인공지능 (11)
        • PyTorch (9)
      • Cloud (8)
        • AWS (4)
        • GCP (2)
      • 버그처리 (14)
      • 회고 & 일상 (5)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
동석해요
FastAPI Raise HTTP Exception(사용자 지정) - 24
상단으로

티스토리툴바