te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Fetch API Global Error Handler - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fetch API Global Error Handler - Stack Overflow

programmeradmin3浏览0评论

I am using the fetch API with a REST API, and i want to handle certain errors globally, errors like 500, 503 ... I tried doing something like this

function(url, method, data) {
    return fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
        "Content-Type": "application/json; charset=utf-8"
        }
    }).then(response => {

        if (response.ok && response.status < 500) console.log("ouch");;

        return response;

});

but it doesn't seem to be working. how do i catch 500, 503 ... in the fetch api?

I am using the fetch API with a REST API, and i want to handle certain errors globally, errors like 500, 503 ... I tried doing something like this

function(url, method, data) {
    return fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
        "Content-Type": "application/json; charset=utf-8"
        }
    }).then(response => {

        if (response.ok && response.status < 500) console.log("ouch");;

        return response;

});

but it doesn't seem to be working. how do i catch 500, 503 ... in the fetch api?

Share Improve this question edited Jul 12, 2018 at 5:06 zolamk asked Jul 12, 2018 at 4:15 zolamkzolamk 6,39710 gold badges35 silver badges52 bronze badges 4
  • 1 it doesn't seem to be working in what way? it doesn't look like you're handling any errors at all - also, you've got a function expression there ... clearly not actual code as that isn't allowed like that (although, the last line }); suggests this snippet is just a poorly chosen fragment of your actual code) – Jaromanda X Commented Jul 12, 2018 at 4:16
  • 1 fetch is a promise event so any error must caught in catch statement – Navdeep Singh Commented Jul 12, 2018 at 4:25
  • @NavdeepSingh yeah i want something like a global catch and then – zolamk Commented Jul 12, 2018 at 5:08
  • Create a fetch wrapper that supports global / top-level response interceptors / error handlers. Or you know, just use Axios. – Phil Commented Jul 12, 2018 at 5:09
Add a ment  | 

2 Answers 2

Reset to default 15

You can try the following approach, by using it you can handle all possible errors in one place and generate a custom response to return e.g. if all requests return JSON data then you can convert the response to JSON before returning it.

function secureFetch(url, method, data) {
  return new Promise((resolve, reject) => {
    fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
          "Content-Type": "application/json; charset=utf-8"
        }
      }).then(response => {
        // response only can be ok in range of 2XX
        if (response.ok) {
          // you can call response.json() here too if you want to return json
          resolve(response);
        } else {
          //handle errors in the way you want to
          switch (response.status) {
            case 404:
              console.log('Object not found');
              break;
            case 500:
              console.log('Internal server error');
              break;
            default:
              console.log('Some error occured');
              break;
          }

          //here you also can thorow custom error too
          reject(response);
        }
      })
      .catch(error => {
        //it will be invoked mostly for network errors
        //do what ever you want to do with error here
        console.log(error);
        reject(error);
      });
  });
}

secureFetch('https://jsonplaceholder.typicode./posts/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));

secureFetch('https://jsonplaceholder.typicode./posts/100000000')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));

Update: You can achieve the same result without creating an extra promise

function secureFetch(url, method, data) {
  return fetch(url, {
    method: method || "GET",
    body: JSON.stringify(data),
    mode: "cors",
    headers: {
      "Content-Type": "application/json; charset=utf-8"
    }
  }).then(response => {
    // Server returned a status code of 2XX
    if (response.ok) {
      // you can call response.json() here if you want to return the json
      return response;
    }

    // Server returned a status code of 4XX or 5XX
    // Throw the response to handle it in the next catch block
    throw response;
  }).catch(error => {
    // It will be invoked for network errors and errors thrown from the then block
    // Do what ever you want to do with error here
    if (error instanceof Response) {
      // Handle error according to the status code
      switch (error.status) {
        case 404:
          // You can also call global notification service here
          // to show a notification to the user
          // notificationService.information('Object not found');
          console.log('Object not found');
          break;
        case 500:
          console.log('Internal server error');
          break;
        default:
          console.log('Some error occurred');
          break;
      }
    } else {
      // Handle network errors
      console.log('Network error');
      console.log(error);
    }
    // In case you don't want to throw the error just return some value here
    // This will be returned to the then block as a resolved promise
    // return { success: false };

    // Here you can throw a custom error too
    // throw new Error('Something went wrong');
    throw error;
  });
}


secureFetch('https://jsonplaceholder.typicode./posts/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));

secureFetch('https://jsonplaceholder.typicode./posts/100000000')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log(error));

Here you can handle with promise something like this:

function status(response) {
    /*You can handle status here.*/
    if (response.status >= 200 && response.status < 300) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(new Error(response.statusText))
    }
  }

  function json(response) {
    return response.json()
  }
function makeCall(url, method, data) {
    return fetch(url, {
        method: method || "GET",
        body: JSON.stringify(data),
        mode: "cors",
        headers: {
        "Content-Type": "application/json; charset=utf-8"
        }
    })
    .then(status)
    .then(json)
    .then(function(data) {
    	console.log('Request succeeded with JSON response', data);
    }).catch(function(error) {
      console.log('Request failed', error);
    });
}

var url = 'http://localhost:4200/profile';
var data = {username: 'example'};
makeCall(url, 'POST', data);

发布评论

评论列表(0)

  1. 暂无评论