Barcha yozuvlar
Dasturlash

"200 OK", lekin ichida xato: status kodlar, RFC 9457 problem+json va DRF'da API xatolarini loyihalash

Mijoz "success": false ni ko'rmay, yashil belgi chizdi. 400/401/403/404/409/422/429 ni qachon tanlash, problem+json, maydonlar bo'yicha validatsiya xatolari va ichki tafsilotni sizdirmaydigan bitta exception handler.

Mobil ilova POST /api/orders/42/pay/ ni chaqiradi. Hamyonda pul yetmaydi. Server 200 OK va {"success": false, "error": "Insufficient funds"} bilan javob beradi. Ilova status kodga qaraydi, 200 ni ko'radi, yashil belgi chizadi va foydalanuvchi buyurtma to'landi, deb ketadi. Bir haftadan keyin kimdir server xabarlarini o'zbekchaga tarjima qiladi, satr "Mablag' yetarli emas" bo'lib qoladi va matnni solishtirgan yagona client ham (if error == "Insufficient funds") ishlamay qoladi.

Bu yerda g'ayrioddiy narsa yo'q. Xatolar "keyin qarab olamiz" tamoyili bilan loyihalanganda aynan shunday bo'ladi. Bu maqolada ularni ongli ravishda qanday loyihalashni ko'rib chiqamiz: qaysi status kodni tanlash, javob tanasi (body) qanday ko'rinishda bo'lishi kerak (RFC 9457, application/problem+json), validatsiya xatolarini maydonlar bo'yicha qanday qaytarish, ichki tafsilotlarni qanday oshkor qilmaslik va bularning hammasini DRF va oddiy Django'ga qanday ulash.

"200 + success: false" nega hamma narsani buzadi

Sodda variant odatda shunday ko'rinadi:

# views.py — the "everything is 200" anti-pattern
def pay_order(request, order_id):
    try:
        order = Order.objects.get(pk=order_id)
        charge(order)
        return JsonResponse({"success": True})
    except Exception as e:
        # 200 OK, the real reason is buried in free text,
        # and str(e) may contain SQL, table names or card data
        return JsonResponse({"success": False, "error": str(e)})

Muammolar ketma-ket chiqadi:

  • Status kod yolg'on gapiradi. Kodingiz va foydalanuvchi orasidagi hamma narsa sizning JSON'ingizni emas, status qatorini o'qiydi: HTTP client kutubxonalari (raise_for_status()), retry siyosatlari, load balancer'lar, cache'lar, 5xx ulushini sanaydigan APM dashboard'lar. Hammasiga 200 qaytarsangiz, monitoringdagi error rate abadiy nolga teng.
  • Sabab erkin matnda yozilgan. Client "error": "..." bo'yicha ishonchli tarmoqlana olmaydi: imlo xatosini tuzatsangiz yoki tarjima qo'shsangiz, matn o'zgaradi.
  • str(e) ichki tafsilotlarni chiqarib yuboradi. IntegrityError xabarida constraint nomi va ko'pincha takrorlangan qiymatning o'zi bor; to'lov SDK'sidan kelgan KeyError provayder javobining bir qismini o'z ichiga olishi mumkin; traceback'da fayl yo'llari bor. Bularning hammasi to'g'ridan-to'g'ri client'ga ketadi.
  • Har bir endpoint o'z formatini o'ylab topadi. Biri error, boshqasi message, uchinchisi errors: {...} qaytaradi. Frontend'da har bir endpoint uchun alohida parser paydo bo'ladi.

Yechim uch qismdan iborat: to'g'ri status kod, standart body va ikkalasini ham yasaydigan koddagi bitta joy.

Status kodni tanlash

Status kod — bu qo'pol kategoriya. U universal dasturlarga qanday nosozlik yuz berganini va so'rovni qayta yuborishning ma'nosi bor-yo'qligini aytadi. Mana holatlarning 95 foizida yetadigan kodlar:

Kod Ma'nosi Odatiy holat Qayta urinish?
400 Bad Request So'rovning o'zi buzuq yaroqsiz JSON, query parametr turi noto'g'ri Yo'q, so'rovni tuzatish kerak
401 Unauthorized Autentifikatsiya qilinmagan token yo'q, muddati o'tgan yoki noto'g'ri Qayta login qilgandan keyin
403 Forbidden Kimligi ma'lum, lekin ruxsat yo'q kassir admin endpoint'ini chaqiradi Yo'q
404 Not Found Resurs yo'q (yoki uning borligini bilishingiz shart emas) noto'g'ri id, boshqa odamning buyurtmasi Yo'q
409 Conflict Resursning joriy holati bilan ziddiyat buyurtma allaqachon to'langan, versiya mos emas, idempotency key boshqa body bilan qayta ishlatilgan Ba'zan, holatni qayta o'qib
422 Unprocessable Content Sintaksis joyida, mazmuni esa noto'g'ri summa minimaldan kam, telefon raqami noto'g'ri Yo'q, ma'lumotni tuzatish kerak
429 Too Many Requests Rate limit'ga yetildi SMS kodi juda ko'p so'ralgan Ha, Retry-After dan keyin
500 Internal Server Error Bizning bug ushlanmagan exception Balki, backoff bilan
502 / 503 / 504 Upstream yoki yuklama muammosi to'lov provayderi ishlamayapti, texnik ishlar, timeout Ha, backoff va idempotency key bilan

Adashish oson bo'lgan bir nechta qoida:

  • 401 yoki 403. 401 — "siz kimligingizni bilmayman" degani. RFC 9110 401 javobida WWW-Authenticate header bo'lishini talab qiladi. 403 — "kimligingizni bilaman, javob esa yo'q". Qayta login qilish 403 ni o'zgartirmaydi.
  • 403 yoki 404. Agar resurs mavjudligining o'zi maxfiy bo'lsa (boshqa odamning buyurtmasi, foydalanuvchi kartasi), 404 qaytaring. Aks holda hujumchi id'larni birma-bir terib, 403 lar orqali qaysilari mavjudligini bilib oladi.
  • 400 yoki 422. 400 — server hatto tahlil qila olmaydigan so'rovlar uchun; 422 — to'g'ri tuzilgan, lekin qiymatlari validatsiyadan yoki biznes qoidadan o'tmagan so'rovlar uchun. DRF standart holatda validatsiya xatolariga 400 qaytaradi, ko'p API'lar ham shunday qiladi. Bu maqbul; muhimi — bitta kelishuvni tanlab, uni hujjatlashtirish. Men validatsiya uchun 422 ni afzal ko'raman: shunda "client'ingiz buzuq" va "foydalanuvchi noto'g'ri narsa kiritdi" bir-biridan ajraladi.
  • 4xx — client aybi, 5xx — bizniki. Validatsiya xatosiga hech qachon 500, baza yiqilganda esa 400 qaytarmang. 5xx ulushi — navbatchini tunda uyg'otadigan metrika; u halol bo'lsin.

Body: RFC 9457 problem+json

RFC 9457 (2023-yilda RFC 7807 o'rnini egallagan) HTTP xatolari uchun application/problem+json media type'li standart JSON formatini belgilaydi. Unda beshta standart maydon bor:

  • type — muammo turini aniqlaydigan URI. Client tayanishi kerak bo'lgan asosiy identifikator shu. Agar berilmasa, about:blank deb hisoblanadi, ya'ni "status koddan boshqa ma'lumot yo'q".
  • title — muammo turining qisqa, inson o'qiydigan tavsifi. U holatdan holatga o'zgarmasligi kerak (lokalizatsiyadan tashqari).
  • status — qulaylik uchun takrorlangan HTTP status kod.
  • detail — aynan shu holatning inson o'qiydigan izohi.
  • instance — aniq shu holatni ko'rsatuvchi URI (men u yerga so'rov yo'lini qo'yaman).

Qolgan hamma narsa — extension member, o'z maydonlaringizni qo'shishingiz mumkin. RFC 9457 ning o'zida validatsiya xatolari uchun errors massivi va pointer maydoni (so'rov body'sidagi joyga JSON Pointer) bilan misol bor. Mening API'larimda validatsiya xatosi shunday ko'rinadi:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
Content-Language: en

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Validation failed",
  "status": 422,
  "detail": "One or more fields are invalid.",
  "instance": "/api/transfers/",
  "code": "validation_error",
  "errors": [
    {"pointer": "#/amount", "code": "min_value", "detail": "Ensure this value is greater than or equal to 1000."},
    {"pointer": "#/recipient/phone", "code": "invalid", "detail": "Enter a valid phone number."}
  ]
}

Har bir xatoni ikki tomon o'qiydi: dastur va inson. type/code dastur uchun va hech qachon o'zgarmaydi; title/detail inson uchun, ularni istalgan paytda qayta yozish va tarjima qilish mumkin.

type yoniga men qisqa code maydonini qo'shaman. Aslini olganda, u ortiqcha (URI ning oxirgi qismi xuddi shu ma'lumotni beradi), lekin switch (problem.code) URL tahlil qilishdan qulayroq, snake_case kodlar esa DRF va Django ichida allaqachon ishlatiladiganlar bilan bir xil. type dagi URI ochilishi shart emas, lekin u har bir xato bo'yicha hujjat joylash uchun qulay joy.

Barcha xatolarni yasaydigan bitta joy

Avval yordamchi funksiya va domen xatolari uchun bazaviy exception'dan iborat kichik modul. Domen xatosi — biznes mantiq biladigan va ko'rsatish xavfsiz bo'lgan narsa: "buyurtma allaqachon to'langan", "mablag' yetarli emas".

# api/problems.py
PROBLEM_BASE = "https://api.example.com/problems/"
PROBLEM_JSON = "application/problem+json"


def problem(status, code, title, detail=None, instance=None, **extra):
    body = {
        "type": PROBLEM_BASE + code.replace("_", "-"),
        "title": title,
        "status": status,
        "detail": detail or title,
        "code": code,
    }
    if instance:
        body["instance"] = instance
    body.update(extra)
    return body


class ProblemError(Exception):
    """Base class for domain errors that are safe to show to the client."""

    status = 400
    code = "bad_request"
    title = "Bad request"

    def __init__(self, detail=None, **extra):
        super().__init__(detail or self.title)
        self.detail = detail
        self.extra = extra

    def to_dict(self, instance=None):
        return problem(self.status, self.code, self.title, self.detail, instance, **self.extra)


class MalformedRequest(ProblemError):
    status = 400
    code = "malformed_request"
    title = "Malformed request body"


class ValidationProblem(ProblemError):
    status = 422
    code = "validation_error"
    title = "Validation failed"


class OrderAlreadyPaid(ProblemError):
    status = 409
    code = "order_already_paid"
    title = "Order is already paid"


class InsufficientFunds(ProblemError):
    status = 422
    code = "insufficient_funds"
    title = "Insufficient funds"

Endi koddagi istalgan joydan raise OrderAlreadyPaid(...) o'z status kodi, kodi va xavfsiz xabarini olib keladi. Har bir view'da qo'lda yig'ilgan JSON bilan try/except kerak emas.

DRF: o'z exception handler'imiz

DRF EXCEPTION_HANDLER sozlamasi orqali exception handler'ni almashtirishga imkon beradi. Standart rest_framework.views.exception_handler APIException vorislarini, shuningdek Django'ning Http404 va PermissionDenied exception'larini javobga aylantiradi, qolgan hamma narsa uchun esa None qaytaradi (bu keyin 500 ga aylanadi). Biz uni birinchi chaqiramiz va natijasini qayta shakllantiramiz:

# api/exceptions.py
import logging
import uuid

from django.conf import settings
from rest_framework import exceptions
from rest_framework.exceptions import ErrorDetail
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.views import exception_handler, set_rollback

from .problems import PROBLEM_JSON, ProblemError, problem

logger = logging.getLogger("api")


def _escape(key):
    # JSON Pointer (RFC 6901): "~" -> "~0", "/" -> "~1"
    return str(key).replace("~", "~0").replace("/", "~1")


def _flatten(detail, path=""):
    """Turn DRF's nested error structure into [{pointer, code, detail}, ...]."""
    if isinstance(detail, dict):
        for key, value in detail.items():
            if key == api_settings.NON_FIELD_ERRORS_KEY:
                yield from _flatten(value, path)
            else:
                yield from _flatten(value, f"{path}/{_escape(key)}")
    elif isinstance(detail, list):
        if all(isinstance(item, ErrorDetail) for item in detail):
            for item in detail:
                yield {"pointer": "#" + path, "code": item.code, "detail": str(item)}
        else:  # list of nested objects, e.g. many=True
            for index, value in enumerate(detail):
                yield from _flatten(value, f"{path}/{index}")
    else:
        yield {"pointer": "#" + path, "code": getattr(detail, "code", "invalid"), "detail": str(detail)}


def problem_exception_handler(exc, context):
    request = context["request"]

    if isinstance(exc, ProblemError):
        set_rollback()  # we bypass DRF's handler, so roll back ATOMIC_REQUESTS ourselves
        return Response(exc.to_dict(instance=request.path), status=exc.status,
                        content_type=PROBLEM_JSON)

    response = exception_handler(exc, context)  # handles APIException, Http404, PermissionDenied

    if response is None:
        if settings.DEBUG:
            return None  # keep Django's debug page locally
        error_id = uuid.uuid4().hex
        logger.exception("Unhandled API error %s on %s", error_id, request.path)
        set_rollback()
        body = problem(500, "internal_error", "Internal server error",
                       "Something went wrong on our side. Please try again later.",
                       request.path, error_id=error_id)
        return Response(body, status=500, content_type=PROBLEM_JSON)

    if isinstance(exc, exceptions.ValidationError):
        status = 422
        body = problem(status, "validation_error", "Validation failed",
                       "One or more fields are invalid.", request.path,
                       errors=list(_flatten(exc.detail)))
    else:
        status = response.status_code  # may already be 403 instead of 401, see below
        code = getattr(exc, "default_code", "error")
        if status == 403 and code == "not_authenticated":
            code = "permission_denied"
        detail = exc.detail if isinstance(exc.detail, str) else None
        body = problem(status, code, response.status_text, detail, request.path)

    problem_response = Response(body, status=status, content_type=PROBLEM_JSON)
    for header in ("WWW-Authenticate", "Retry-After"):
        if header in response:
            problem_response[header] = response[header]
    return problem_response
# settings.py
REST_FRAMEWORK = {
    "EXCEPTION_HANDLER": "api.exceptions.problem_exception_handler",
    "DEFAULT_AUTHENTICATION_CLASSES": [
        # The first class decides 401 vs 403 for anonymous requests:
        # TokenAuthentication sends "WWW-Authenticate: Token" -> 401,
        # SessionAuthentication sends nothing -> DRF downgrades to 403.
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],
}

Qadamma-qadam nima bo'ladi:

  1. Bizning ProblemError to'g'ridan-to'g'ri problem javobiga aylanadi.
  2. DRF biladigan hamma narsa avval standart handler'dan o'tadi. Shunda uning foydali xatti-harakati saqlanadi: 401 uchun WWW-Authenticate, Throttled uchun Retry-After. Bu header'larni o'z javobimizga ko'chiramiz.
  3. ValidationError tekis errors ro'yxatiga yoyiladi. DRF'dagi exc.detail — dict va list'lardan iborat ichma-ich struktura, uning barglari .code atributiga ega ErrorDetail satrlari (required, invalid, max_length, min_value...). _flatten funksiyasi uni aylanib chiqib, JSON Pointer'lar yasaydi, many=True va ichki serializer'lar uchun indekslarni ham hisobga oladi.
  4. Noma'lum har qanday narsa — bug. Uni tasodifiy error_id ostida to'liq traceback bilan log'ga yozamiz va shu id bilan umumiy 500 qaytaramiz. Foydalanuvchi uni support'ga aytishi mumkin, siz uni log'lardan grep bilan topasiz, tashqariga esa hech qanday ichki ma'lumot chiqmaydi.

View esa oddiy biznes kod kabi ko'rinadi:

# api/views.py
from django.db import transaction
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import Order
from .problems import InsufficientFunds, OrderAlreadyPaid


class PayOrderView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, order_id):
        with transaction.atomic():
            # Someone else's order -> 404, not 403: do not confirm it exists.
            order = get_object_or_404(
                Order.objects.select_for_update(), pk=order_id, customer=request.user
            )
            if order.status == Order.Status.PAID:
                raise OrderAlreadyPaid(f"Order {order.pk} was already paid.", order_id=order.pk)

            wallet = request.user.wallet
            if wallet.balance < order.total:
                raise InsufficientFunds("Your balance is lower than the order total.")

            order.mark_paid(wallet)
        return Response({"id": order.pk, "status": order.status})

Oddiy Django: middleware va formalar

DRF'siz xuddi shu g'oya middleware'ga joylashadi. process_exception view exception tashlaganda chaqiriladi, jumladan Http404 va PermissionDenied uchun ham, agar u javob qaytarsa, Django aynan shu javobni ishlatadi:

# api/middleware.py — plain Django, no DRF
import logging
import uuid

from django.core.exceptions import PermissionDenied
from django.http import Http404, JsonResponse

from .problems import PROBLEM_JSON, ProblemError, problem

logger = logging.getLogger("api")


class ProblemJSONMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exc):
        if not request.path.startswith("/api/"):
            return None  # HTML pages keep Django's normal error handling

        if isinstance(exc, ProblemError):
            body = exc.to_dict(instance=request.path)
        elif isinstance(exc, Http404):
            body = problem(404, "not_found", "Resource not found", instance=request.path)
        elif isinstance(exc, PermissionDenied):
            body = problem(403, "permission_denied", "Permission denied", instance=request.path)
        else:
            error_id = uuid.uuid4().hex
            logger.exception("Unhandled API error %s on %s", error_id, request.path)
            body = problem(500, "internal_error", "Internal server error",
                           "Something went wrong on our side. Please try again later.",
                           request.path, error_id=error_id)

        return JsonResponse(body, status=body["status"], content_type=PROBLEM_JSON,
                            json_dumps_params={"ensure_ascii": False})
# settings.py
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "api.middleware.ProblemJSONMiddleware",
]

Django formalari mashina o'qiydigan xatolarni allaqachon bera oladi: form.errors.get_json_data() {field: [{"message": ..., "code": ...}]} qaytaradi. Faqat ularni pointer'larga aylantirish qoladi:

# api/views.py — plain Django view with a Form
import json

from django.core.exceptions import NON_FIELD_ERRORS
from django.http import JsonResponse
from django.views.decorators.http import require_POST

from transfers.forms import TransferForm
from .problems import MalformedRequest, ValidationProblem


def form_errors(form):
    return [
        {
            "pointer": "#" if field == NON_FIELD_ERRORS else f"#/{field}",
            "code": error["code"] or "invalid",
            "detail": error["message"],
        }
        for field, errors in form.errors.get_json_data().items()
        for error in errors
    ]


@require_POST
def create_transfer(request):
    try:
        payload = json.loads(request.body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise MalformedRequest("Request body must be valid JSON.")
    if not isinstance(payload, dict):
        raise MalformedRequest("Request body must be a JSON object.")

    form = TransferForm(payload)
    if not form.is_valid():
        raise ValidationProblem("One or more fields are invalid.", errors=form_errors(form))

    transfer = form.save()
    return JsonResponse({"id": transfer.pk}, status=201)

Production'da uchraydigan tuzoqlar

  • DRF 401 o'rniga 403 qaytaradi. Anonim so'rov uchun DRF WWW-Authenticate qiymatini birinchi autentifikatsiya klassidan so'raydi. SessionAuthentication da bunday qiymat yo'q, shuning uchun u birinchi tursa, DRF NotAuthenticated ni 403 ga o'zgartiradi. To'g'ri 401 kerak bo'lsa, header beradigan klassni (token, JWT) birinchi qo'ying.
  • O'z handler'ingiz ATOMIC_REQUESTS ni buzadi. DRF exception'ni view ichida ushlaydi, shuning uchun butun so'rovga ochilgan transaction commit bo'lib ketadi. Standart handler set_rollback() ni o'zi chaqiradi; javoblarni o'zingiz yig'sangiz, yuqoridagi kodda bo'lgani kabi uni ham chaqiring. Oddiy Django'da exception middleware'ga yetib kelguncha atomic blokdan chiqib bo'ladi, ya'ni rollback allaqachon bo'lgan.
  • Yutib yuborilgan 500 lar error tracking'dan yo'qoladi. Handler noma'lum exception'ga javob qaytarganda, Django'ning got_request_exception signali yuborilmaydi va unga ulangan vositalar jim qolishi mumkin. Yo xatoni handler'dan aniq yuboring, yoki logger.exception ni ushlaydigan logging integratsiyasidan foydalaning.
  • View'dan tashqaridagi xatolar. Middleware, URL resolving va DEBUG=False paytidagi noma'lum URL uchun 404 process_exception dan ham, DRF'dan ham o'tmaydi. Root URLconf'da handler404 va handler500 ni belgilang, ular /api/ yo'llari uchun problem+json qaytarsin (handler404 faqat DEBUG=False bo'lganda ishlatiladi).
  • Content negotiation. Client faqat Accept: application/problem+json yuborsa, standart JSONRenderer (application/json) mos kelmasligi mumkin. Yo client tomonda application/json ni ham qabul qiling, yoki shu media type'li renderer vorisini qo'shing.
  • Kodlar — API kontraktining bir qismi. insufficient_funds ni qayta nomlash — xuddi maydonni qayta nomlash kabi breaking change. Xabarlar esa unday emas: ularni erkin qayta yozish va tarjima qilish mumkin. title/detail ni Accept-Language bo'yicha tarjima qiling, code ni esa hech qachon.
  • Kiritilgan qiymatni takrorlaydigan validatsiya xabarlari. "8600 1234 5678 9012 karta bloklangan" — bu ma'lumot sizib chiqishi. Maydonda nima borligini emas, qaysi maydon noto'g'ri ekanini ayting, ayniqsa karta raqamlari, token'lar va parollar uchun.
  • Kodsiz validatsiya xatolari. code= siz raise ValidationError("...") bo'sh yoki umumiy kod beradi. O'z validator'laringizda doim code="..." bering, client'da tayanadigan barqaror narsa bo'lsin.

Testlar kontrakt asta-sekin o'zgarib ketishiga yo'l qo'ymaydi:

# tests/test_problems.py
import pytest
from rest_framework.test import APIClient


@pytest.fixture
def api_client(django_user_model):
    user = django_user_model.objects.create_user("ali", password="s3cret-pass")
    client = APIClient()
    client.force_authenticate(user)
    return client


@pytest.mark.django_db
def test_validation_error_is_problem_json(api_client):
    resp = api_client.post("/api/transfers/", {"amount": "-5"}, format="json")

    assert resp.status_code == 422
    assert resp["Content-Type"].startswith("application/problem+json")
    body = resp.json()
    assert body["code"] == "validation_error"
    assert {"pointer": "#/amount", "code": "min_value"}.items() <= body["errors"][0].items()


@pytest.mark.django_db
def test_anonymous_gets_401_with_challenge():
    resp = APIClient().post("/api/orders/1/pay/")

    assert resp.status_code == 401
    assert "WWW-Authenticate" in resp

Client tomondagi mukofot esa — tarmoqlanish zerikarli darajada oddiy bo'lib qoladi:

# a client that branches on the code, never on the text
import httpx

resp = httpx.post(url, json=payload, headers=headers, timeout=10)
if resp.is_error and resp.headers.get("content-type", "").startswith("application/problem+json"):
    problem = resp.json()
    match problem.get("code"):
        case "insufficient_funds":
            show_top_up_screen()
        case "order_already_paid":
            show_receipt(problem["order_id"])
        case "validation_error":
            highlight_fields(problem["errors"])
        case _:
            show_generic_error(problem.get("error_id"))

Checklist

  • 4xx — client muammolari uchun, 5xx — faqat server muammolari uchun; ichida xato yashiringan 200 ni hech qachon qaytarmang.
  • 401 doim WWW-Authenticate bilan; boshqalarning resurslari 404 ortiga yashiriladi.
  • Holat ziddiyatlari uchun 409, validatsiya uchun 422 (yoki 400, lekin izchil), 429 esa Retry-After bilan.
  • Har bir xato body'si — type, title, status, detail va barqaror code bilan application/problem+json.
  • Maydon xatolari JSON pointer va o'z code bilan errors[] ichiga tushadi.
  • Noma'lum exception'lar: error_id bilan log, umumiy 500, hech qachon str(e).
  • Barcha xatolarni bitta handler (DRF EXCEPTION_HANDLER yoki middleware) yasaydi; view'lar faqat exception tashlaydi.
  • set_rollback(), handler404/handler500 va xato formati uchun testlarni unutmang.

Xulosa

Xato javobi — log satri emas, interfeys. Status kod infratuzilmaga nima bo'lganini, barqaror code/type client'ga nima qilish kerakligini, detail esa insonga sababini aytadi. Uchalasini RFC 9457 bo'yicha bitta body'ga jamlang, uni koddagi aynan bitta joyda yasang, ichki tafsilotlarni esa log'larda qoldiring.

// izohlar

Izohlar yuklanmoqda...

    // keyingi qadam

    Keling, birga nimadir quramiz.

    Telegramda yozish
    aslbek@asldev: ~
    ❯