Customizing Response Error Handling in FastAPI – Part 11. Learning FastAPI for Beginners

Posted by

<!DOCTYPE html>

Cara Custom Response Handling Error FastAPI – Part 11. Belajar FastAPI Untuk Pemula

Cara Custom Response Handling Error FastAPI – Part 11. Belajar FastAPI Untuk Pemula

Judul : Cara Custom Response Handling Error FastAPI – Part 11. Belajar FastAPI Untuk Pemula

FastAPI menawarkan cara untuk menangani error dengan respons yang disesuaikan sesuai kebutuhan. Dalam tutorial ini, kita akan belajar cara melakukan custom response handling error di FastAPI.

Langkah-langkah:

  1. Buat class BaseHTTPError dari fastapi import HTTPException
  2. Buat class custom HTTPException yang memperluas BaseHTTPError
  3. Tambahkan fungsi exception_handler() untuk menangani error handler secara global

Contoh kode:

“`python
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

class BaseHTTPError(HTTPException):
def __init__(self, status_code: int, detail: str, headers: dict = None):
self.status_code = status_code
self.detail = detail
self.headers = headers or {}

class CustomHTTPException(BaseHTTPError):
def __init__(self, status_code: int, detail: str, headers: dict = None):
super().__init__(status_code, detail, headers)

@app.exception_handler(CustomHTTPException)
async def custom_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={“message”: exc.detail}
)

@app.get(“/”)
async def read_root():
raise CustomHTTPException(status_code=400, detail=”Custom Error Message”)
“`

Dengan mengikuti langkah-langkah di atas, Anda dapat menangani error respons secara kustom di FastAPI. Jangan lupa untuk menjalankan aplikasi FastAPI dan mencoba endpoint yang telah di buat.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x