需要一些关于javascript获取和错误处理中的promise的指导

时间:2016-02-20 10:01:10

标签: javascript promise

我有这个javascript代码来调用fetch(省略了一些不相关的代码)

const callApi = (endpoint, options) => {
  const fullUrl = `${API_ROOT}/${endpoint}`;

  return fetch(fullUrl, options)
    .then(response =>
        response.json().then(json => ({ json, response }))
    ).then(({ json, response }) => {
      if (!response.ok) {
        let errorObj = new Error(`ERROR: http error code: ${response.status} - ${response.statusText}`);
        throw errorObj;
      }

      return json;
    });
};

export default (dispatch, data) => {
  let { endpoint, closeDialogOnSuccess = false, headers = {}, method = 'GET'} = data;
  const { actions, fields } = data;
  const [ requestAction, successAction, failureAction ] = actions;
  const options = { method, headers };
  if (fields) {
    if(method === 'GET') {
      endpoint = endpoint + serialize(_omitBy(fields, _isEmpty));
    }
    if(method === 'POST' || method === 'PUT') {
      options.body = JSON.stringify(fields);
    }
  }

  dispatch(requestAction(data));

  return callApi(endpoint, options)
    .then((json) => {
      dispatch(successAction(json));
      if(closeDialogOnSuccess) dispatch(clearDialog());
    })
    .catch((error) => {
      const errorData = data;
      let failureActionObject = failureAction(error);
      failureActionObject.meta = errorData;
      dispatch(failureActionObject);
    });
};

它主要起作用,但有两件事困扰我:

  • 我是否按照最佳做法使用承诺并妥善处理?
  • 这里的catch()函数并没有捕获从Chrome控制台中显示的所有从fetch(例如404,连接拒绝)中获取的错误。有没有办法捕获获取错误,因此它根本不会出现在控制台日志中?

当遇到404错误时我得到的错误的屏幕截图: enter image description here

0 个答案:

没有答案