LoginSignup
0
0

More than 1 year has passed since last update.

urqlでグローバルなエラーハンドリングを実装する

Posted at

やりたいこと

アプリケーション内で発生したすべてのurqlのエラーを、一箇所のコードで処理できるようにします。
例えば、エラー内容に応じてログを監視システムに送信したり、エラー内容を画面に表示することができるようになります。
調べた際にあまり情報が出てこなかったので、備忘録を兼ねて残しておきます。

環境

  • next: 13.0.6
  • urql: 3.0.3

Exchangeとは

urqlによるリクエスト・レスポンスの一連の処理をカスタマイズできる仕組みです。
Reduxのミドルウェアと同じような要領で、処理の途中に任意のExchangeを挟むことによって、リクエストやレスポンスの内容にアクセスする処理を書くことができます。
リクエストに認証用のヘッダーを付与したり、レスポンスの内容を変換するために使われます。

詳しくは公式ドキュメントをご覧ください。

mapExchangeとは

mapExchangeはurqlにデフォルトで組み込まれているExchangeで、リクエスト・レスポンス・エラーに対する処理をそれぞれ実行することができます。
エラー処理を行う際は、onErrorの中でCombinedErrorオブジェクト(error)を使用でき、この情報を使ってエラーをハンドリングすることができます。
以前のバージョンではerrorExchangeが使われていたようですが、現在はmapExchangeに置き換えられており、errorExchangeは非推奨(deprecated)となっています。

サンプルコード

client.ts
import { createClient } from '@urql/core'
import { cacheExchange, dedupExchange, fetchExchange, mapExchange } from 'urql'

export const client = createClient({
  url: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || 'https://localhost:8000/graphql',
  exchanges: [
    dedupExchange,
    cacheExchange,
    mapExchange({
      onError(error, operation) {
        console.log(`The operation ${operation.key} has errored with:`, error);
      },
    }),
    fetchExchange,
  ],
})

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0