Thuta Learning
ရှာဖွေရန်
GraphQL
IntermediateWeb Developmentbeginner

Error Handling

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Error Handling concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ GraphQL query/code ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် မှန်ကန်စွာအသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

REST မှာ error တစ်ခုကို HTTP status code (404, 500) ဖြင့် ဆိုလေ့ရှိပေမယ့် GraphQL response က HTTP 200 ပဲ ပြန်ပေးပြီး `data` field ဘေးမှာ `errors` array သီးခြားတွဲပါလာပါတယ်။ Field တစ်ခုမှာ error ဖြစ်ပေမယ့် sibling fields များ ဆက်ဖြေရှင်းနိုင်ရင် GraphQL က partial response (data ရှိ + errors ရှိ) ကို ပြန်ပေးပါတယ်။ Error object ရဲ့ `extensions` ထဲမှာ custom `code` (ဥပမာ `NOT_FOUND`, `UNAUTHENTICATED`) ထည့်ပြီး client က programmatically handle လုပ်နိုင်ပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Tutorial 999 ကို query တောင်းရင် database မှာ မရှိသဖြင့် resolver က `GraphQLError` throw လုပ်ပြီး `extensions.code: 'NOT_FOUND'` ထည့်ပါမယ်။ Response ထဲမှာ `data.tutorial` က `null`၊ `errors[0].path` က `["tutorial"]` ဖြစ်ပြီး frontend က `error.extensions.code` ကိုစစ်ပြီး "Tutorial not found" UI ပြပါမယ်။

အတူတူ စမ်းရေးကြည့်မယ်

json
{
  "data": {
    "tutorial": null
  },
  "errors": [
    {
      "message": "Tutorial 999 not found",
      "path": ["tutorial"],
      "extensions": {
        "code": "NOT_FOUND"
      }
    }
  ]
}
You should see
GraphQL error response ကို ဖတ်ပြီး `extensions.code` ဖြင့် error handling logic ရေးနိုင်မည်။

၅ မိနစ် စမ်းကြည့်

`author` field ရဲ့ resolver ထဲ author မတွေ့ရင် `extensions.code: 'NOT_FOUND'` ပါသော `GraphQLError` throw လုပ်ကာ response JSON shape ကို ရေးကြည့်ပါ။

သတိလေးတစ်ချက်

HTTP status code ကိုပဲကြည့်ပြီး request အောင်မြင်တယ်လို့ client-side code ရေးမိရင် GraphQL error များကို လုံးဝ လွှတ်ချန်နိုင်ပါတယ်—HTTP 200 ဖြစ်နေလည်း `errors` array ကို အမြဲစစ်ပါ။

Apollo Server — Handling GraphQL ErrorsGraphQL

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • HTTP status code ကိုပဲကြည့်ပြီး request အောင်မြင်တယ်လို့ client-side code ရေးမိရင် GraphQL error များကို လုံးဝ လွှတ်ချန်နိုင်ပါတယ်—HTTP 200 ဖြစ်နေလည်း `errors` array ကို အမြဲစစ်ပါ။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

`author` field ရဲ့ resolver ထဲ author မတွေ့ရင် `extensions.code: 'NOT_FOUND'` ပါသော `GraphQLError` throw လုပ်ကာ response JSON shape ကို ရေးကြည့်ပါ။

You'll know it worked when: GraphQL error response ကို ဖတ်ပြီး `extensions.code` ဖြင့် error handling logic ရေးနိုင်မည်။

Error Handling | Thuta Learning