Fetch API その2

ボタンを押すと fetch() を使って API にリクエストが投げます。 返ってきた JSON をパースした後、alert() で表示します。
2xx 以外のレスポンスコードが返ったときには明示的に throw Error() するようにしました。 投げたエラーは Promise.prototype.catch() で捕捉することができます。

ソースコード

// レスポンスに対して共通で行う前処理
// 4xx系, 5xx系のエラーをさばくハンドラ
var handleErrors = function(response) {
  // 4xx系, 5xx系エラーのときには response.ok = false になる
  if (!response.ok) {
    throw Error(response.statusText);
  }

  return response;
}

var prepare = function(response) {
  // ステータスコードとステータステキストを表示
  console.info('ok?: ', response.ok);
  console.info('status: ', response.status);
  console.info('statusText: ', response.statusText);

  // レスポンスボディをJSONとしてパース
  return response.json();
}

// 正常終了時の処理
var onFulfilled = function(data) {
  var message = ([
    '成功ハンドラで処理されました。',
    'data: ' + JSON.stringify(data, null, '  '),
  ]).join('\n');

  console.log(data);
  alert(message);
};

// エラー終了時の処理
var onRejected = function(err) {
  var message = ([
    '失敗ハンドラで処理されました。',
    'error: ' + err.message,
  ]).join('\n');

  console.error(err);
  alert(message);
};

fetch('/path/to/api')
  .then(handleErrors)
  .then(prepare)
  .then(onFulfilled)
  .catch(onRejected);