跳至主要內容
版本:v18.0.0

錯誤處理

就像 GraphQL 伺服器一樣,Relay 解析器支援欄位層級的錯誤處理。如果個別的解析器拋出錯誤,當讀取該欄位時,Relay 會將該錯誤記錄到環境中使用者提供的 relayFieldLogger 記錄器,並且該欄位將會變成 null。

這提供了與 GraphQL 伺服器重要的對稱性。解析器的設計旨在實現平穩的遷移路徑,讓團隊能夠從使用解析器在用戶端定義的欄位開始,然後最終將它們遷移到伺服器。

如果解析器拋出錯誤,Relay 會將錯誤記錄到使用者提供的錯誤記錄器,並且會為定義解析器的欄位回傳 null。為了在執行時啟用此行為,Relay 編譯器不允許將解析器欄位類型設定為非 null。

傳遞給 relayFieldLogger 的物件會具有以下形狀

type ResolverErrorEvent = {
kind: 'relay_resolver.error',
// The name of the fragment/query in which the field was read
owner: string,
// The path from the owner root to the field which threw the error
fieldPath: string,
// The error thrown by the resolver
error: Error,
}

一個範例記錄器可能如下所示

function fieldLogger(event) {
if(event.kind === "relay_resolver.error") {
// Log this somewhere!
console.warn(`Resolver error encountered in ${event.owner}.${event.fieldPath}`)
console.warn(event.error)
}
}

const environment = new Environment({
network: Network.create(/* your fetch function here */),
store: new LiveResolverStore(new RecordSource()),
relayFieldLogger: fieldLogger
});
注意

即時解析器 可能會在首次評估時或在呼叫其 .read() 方法時拋出錯誤。Relay 會以相同的方式處理這兩種錯誤。