FastAPI-তে Custom Exception তৈরি এবং হ্যান্ডল করা খুবই সহজ। FastAPI তে আপনি আপনার প্রয়োজন অনুযায়ী কাস্টম ত্রুটি (Exception) তৈরি করতে পারেন এবং সেগুলি বিভিন্ন API রাউট এবং এন্ডপয়েন্টে ব্যবহৃত করতে পারেন। কাস্টম এক্সসেপশন তৈরি করে আপনি একটি নির্দিষ্ট ত্রুটি বা স্টেটাস কোড ফেরত পাঠাতে পারেন, যা ব্যবহারকারী বা ডেভেলপারকে সঠিকভাবে নির্দেশনা দেয়।
এখানে, আমরা দেখব কিভাবে Custom Exception তৈরি করা যায় এবং FastAPI তে কিভাবে তা হ্যান্ডল করা যায়।
Step 1: Custom Exception তৈরি করা
FastAPI তে কাস্টম এক্সসেপশন তৈরি করতে আমরা সাধারণত HTTPException ক্লাস ইনহেরিট করি অথবা নতুন Exception ক্লাস তৈরি করি।
উদাহরণ: Custom HTTP Exception তৈরি
from fastapi import FastAPI, HTTPException
from starlette.status import HTTP_404_NOT_FOUND
app = FastAPI()
# Custom Exception class
class ItemNotFoundError(HTTPException):
def __init__(self, item_id: int):
self.item_id = item_id
self.detail = f"Item with ID {item_id} not found"
self.status_code = HTTP_404_NOT_FOUND
# একটি Route তৈরি যেখানে Custom Exception ব্যবহার করা হবে
@app.get("/items/{item_id}")
def read_item(item_id: int):
# এখানে কিছু logic রয়েছে, যা নির্দিষ্ট আইটেম খুঁজে পাবে
# যদি আইটেম না পাওয়া যায়, তাহলে Custom Exception raised হবে
if item_id != 1:
raise ItemNotFoundError(item_id)
return {"item_id": item_id, "name": "Example Item"}
এখানে:
ItemNotFoundErrorএকটি কাস্টম এক্সসেপশন যাHTTPExceptionক্লাস থেকে ইনহেরিট করা হয়েছে এবং একটি বিশেষstatus_codeএবংdetailপ্রদান করছে।read_itemফাংশনে, যদিitem_id১ না হয়, তাহলে কাস্টম এক্সসেপশনItemNotFoundErrorরেইজ করা হবে।
রিকোয়েস্ট উদাহরণ:
GET /items/2
রেসপন্স:
{
"detail": "Item with ID 2 not found"
}
এখানে, যেহেতু item_id ১ এর সাথে মেলেনি, কাস্টম এক্সসেপশন ItemNotFoundError রেইজ করা হয়েছে।
Step 2: Custom Exception হ্যান্ডল করা
FastAPI তে কাস্টম এক্সসেপশন হ্যান্ডল করতে exception_handler ব্যবহার করা যায়। আপনি আপনার কাস্টম এক্সসেপশনের জন্য একটি কাস্টম হ্যান্ডলার তৈরি করতে পারেন, যা কাস্টম ত্রুটি বা অন্য কিছু স্টেটাস কোড ও ডিটেইল ফেরত পাঠাবে।
উদাহরণ: কাস্টম এক্সসেপশন হ্যান্ডলিং
from fastapi import FastAPI, HTTPException
from starlette.responses import JSONResponse
from starlette.status import HTTP_404_NOT_FOUND
app = FastAPI()
# Custom Exception class
class ItemNotFoundError(HTTPException):
def __init__(self, item_id: int):
self.item_id = item_id
self.detail = f"Item with ID {item_id} not found"
self.status_code = HTTP_404_NOT_FOUND
# কাস্টম এক্সসেপশন হ্যান্ডলার
@app.exception_handler(ItemNotFoundError)
async def item_not_found_exception_handler(request, exc: ItemNotFoundError):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail}
)
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id != 1:
raise ItemNotFoundError(item_id)
return {"item_id": item_id, "name": "Example Item"}
এখানে:
item_not_found_exception_handler: কাস্টম এক্সসেপশনItemNotFoundErrorএর জন্য একটি কাস্টম এক্সসেপশন হ্যান্ডলার তৈরি করা হয়েছে।JSONResponse: কাস্টম এক্সসেপশনের জন্য একটি JSON আউটপুট পাঠাচ্ছে, যাতে ত্রুটি সম্পর্কে বিস্তারিত বার্তা এবং সঠিক স্ট্যাটাস কোড ফেরত আসে।
রিকোয়েস্ট উদাহরণ:
GET /items/2
রেসপন্স:
{
"message": "Item with ID 2 not found"
}
Step 3: General Exception Handling
FastAPI তে আপনি সাধারণ এক্সসেপশন হ্যান্ডলিংও করতে পারেন। যদি কোনো অপ্রত্যাশিত ত্রুটি ঘটে, তাহলে আপনি একটি general exception handler তৈরি করতে পারেন।
উদাহরণ: General Exception Handling
from fastapi import FastAPI, HTTPException
from starlette.responses import JSONResponse
app = FastAPI()
# General Exception Handler
@app.exception_handler(Exception)
async def general_exception_handler(request, exc: Exception):
return JSONResponse(
status_code=500,
content={"message": f"Something went wrong: {exc}"}
)
@app.get("/cause-error")
def cause_error():
# এখানে একটি সাধারণ ত্রুটি সৃষ্টির জন্য '1/0' ডিভিশন জেনারেট করা হচ্ছে
return 1 / 0
এখানে:
general_exception_handler: সমস্ত অপ্রত্যাশিত ত্রুটি ক্যাচ করার জন্য একটি হ্যান্ডলার তৈরি করা হয়েছে।1 / 0: একটি জেনুইন ডিভিশন বাই জিরো ত্রুটি তৈরি করার উদাহরণ।
রিকোয়েস্ট উদাহরণ:
GET /cause-error
রেসপন্স:
{
"message": "Something went wrong: division by zero"
}
Step 4: Custom Error Responses
FastAPI তে আপনি কাস্টম ত্রুটি প্রতিক্রিয়া (error responses) তৈরি করতে পারেন যাতে সেগুলোর মধ্যে নির্দিষ্ট ফিল্ড থাকে, যেমন error_code, error_message, বা details।
উদাহরণ: কাস্টম ত্রুটি প্রতিক্রিয়া
from fastapi import FastAPI, HTTPException
from starlette.responses import JSONResponse
app = FastAPI()
# Custom Exception with error_code and error_message
class CustomError(HTTPException):
def __init__(self, error_code: int, error_message: str):
self.error_code = error_code
self.error_message = error_message
self.status_code = 400
# Custom Error Handler
@app.exception_handler(CustomError)
async def custom_error_handler(request, exc: CustomError):
return JSONResponse(
status_code=exc.status_code,
content={
"error_code": exc.error_code,
"error_message": exc.error_message
}
)
@app.get("/cause-custom-error")
def cause_custom_error():
raise CustomError(error_code=1001, error_message="This is a custom error!")
রিকোয়েস্ট উদাহরণ:
GET /cause-custom-error
রেসপন্স:
{
"error_code": 1001,
"error_message": "This is a custom error!"
}
এখানে, CustomError ক্লাসটি কাস্টম ত্রুটি কোড এবং বার্তা ফিরিয়ে দেয় এবং custom_error_handler ফাংশন সেই ত্রুটি হ্যান্ডল করে।
FastAPI তে Custom Exception তৈরি এবং হ্যান্ডল করা খুবই সহজ এবং শক্তিশালী। আপনি সহজেই কাস্টম এক্সসেপশন তৈরি করতে পারেন এবং HTTPException ক্লাসের মাধ্যমে ত্রুটি মেসেজ এবং স্ট্যাটাস কোড কাস্টমাইজ করতে পারেন। এছাড়া, FastAPI তে সাধারণ এবং কাস্টম এক্সসেপশন হ্যান্ডলিং করা খুবই সহজ, যা আপনাকে উন্নত এবং সুরক্ষিত API তৈরি করতে সাহায্য করে।
Read more