获取:拒绝承诺,如果状态不正常,则捕获错误

Fetch: reject promise and catch the error if status is not OK?

本文关键字:错误 不正常 如果 拒绝 承诺 获取 状态      更新时间:2023-09-26

这是我要做的:

import 'whatwg-fetch';
function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())            
                .catch(error => {
                    throw(error);
                })
            });
    };
}
function status(res) {
    if (!res.ok) {
        return Promise.reject()
    }
    return res;
}

编辑:承诺不会被拒绝,这就是我试图弄清楚的。

我正在 Redux 中使用这个带有 redux-promise-中间件的获取 polyfill。

Fetch 承诺仅在发生网络错误时拒绝 TypeError。由于 4xx 和 5xx 响应不是网络错误,因此没有什么可捕获的。您需要自己抛出错误才能使用 Promise#catch

获取响应方便地提供一个ok,告诉您请求是否成功。像这样的东西应该可以解决问题:

fetch(url).then((response) => {
  if (response.ok) {
    return response.json();
  }
  throw new Error('Something went wrong');
})
.then((responseJson) => {
  // Do something with the response
})
.catch((error) => {
  console.log(error)
});

以下login with username and password示例演示如何:

  1. 检查response.ok
  2. reject如果不是正常,而不是抛出错误
  3. 进一步处理来自服务器的任何错误提示,例如验证问题
login() {
  const url = "https://example.com/api/users/login";
  const headers = {
    Accept: "application/json",
    "Content-Type": "application/json",
  };
  fetch(url, {
    method: "POST",
    headers,
    body: JSON.stringify({
      email: this.username,
      password: this.password,
    }),
  })
    .then((response) => {
      // 1. check response.ok
      if (response.ok) {
        return response.json();
      }
      return Promise.reject(response); // 2. reject instead of throw
    })
    .then((json) => {
      // all good, token is ready
      this.store.commit("token", json.access_token);
    })
    .catch((response) => {
      console.log(response.status, response.statusText);
      // 3. get error messages, if any
      response.json().then((json: any) => {
        console.log(json);
      })
    });
},

感谢大家的帮助,拒绝.catch()的承诺解决了我的问题:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}

function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}
对我来说

,FNY的答案真的得到了一切。由于 fetch 没有抛出错误,我们需要自己抛出/处理错误。使用异步/等待发布我的解决方案。我认为它更向前和可读

解决方案 1:不抛出错误,自己处理错误

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response
    if (fetchResult.ok) {
      return result; // return success object
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };
    const error = new Error();
    error.info = responseError;
    return (error);
  }

在这里,如果我们收到错误,我们正在构建一个错误对象,普通 JS 对象并返回它,缺点是我们需要在外面处理它。如何使用:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error
    return;
  }
  debug.log('Success saving user', userSaved); // handle success

解决方案 2:使用 try/catch 引发错误

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();
    if (fetchResult.ok) {
      return result;
    }
    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };
    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

在这里,我们抛出我们创建的错误,因为错误 ctor 只批准字符串,我创建普通的错误 js 对象,用途将是:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

解决方案 3:使用客户错误

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();
    if (fetchResult.ok) {
      return result;
    }
    throw new ClassError(result.message, result.data, result.code);
  }

和:

class ClassError extends Error {
  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }
}

希望它有帮助。

> 2021 打字稿答案

我所做的是编写一个接受泛型的fetch包装器,如果response ok它将自动.json()并类型断言结果,否则包装器会抛出response

export const fetcher = async <T>(input: RequestInfo, init?: RequestInit) => {
  const response = await fetch(input, init);
  if (!response.ok) {
    throw response;
  }
  return response.json() as Promise<T>;
};

然后我会捕获错误并检查它们是否是instanceof Response.这样 TypeScript 就知道error具有Response属性,例如status statusText body headers等,我可以为每个4xx 5xx状态代码应用自定义消息。

try {
  return await fetcher<LoginResponse>("http://localhost:8080/login", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ email: "user@example.com", password: "passw0rd" }),
  });
} catch (error) {
  if (error instanceof Response) {
    switch (error.status) {
      case 401:
        throw new Error("Invalid login credentials");
      /* ... */
      default:
        throw new Error(`Unknown server error occured: ${error.statusText}`);
    }
  }
  throw new Error(`Something went wrong: ${error.message || error}`);
}

如果发生类似网络错误之类的事情,则可以在instanceof Response检查之外使用更通用的消息捕获它,即

throw new Error(`Something went wrong: ${error.message || error}`);

@fny的答案(接受的答案)对我不起作用。throw new Error()没有被.catch接走。我的解决方案是用一个构建新承诺的函数来包装fetch


function my_fetch(url, args) {
  return new Promise((resolve, reject) => {
    fetch(url, args)
    .then((response) => {
      response.text().then((body) => { 
        if (response.ok) {
          resolve(body) 
        } else {
          reject(body) 
        }
      })
    })
    .catch((error) => { reject(error) })
  })
}

现在,每个错误和不正常的返回都将通过.catch方法拾取:

my_fetch(url, args)
.then((response) => {
  // Do something with the response
})
.catch((error) => {
  // Do something with the error
})
function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}
fetch("https://example.com/api/users")
    .then(handleErrors)
    .then(response => console.log("ok") )
    .catch(error => console.log(error) );

另一个(较短的)版本与大多数答案产生共鸣:

fetch(url)
.then(response => response.ok ? response.json() : Promise.reject(response))
.then(json => doStuff(json)) //all good
//next line is optional
.catch(response => handleError(response)) //handle error
我对

任何建议的解决方案都不满意,所以我尝试了一下 Fetch API 来找到一种处理成功响应和错误响应的方法。

计划是在这两种情况下都获得{status: XXX, message: 'a message'}格式。

注意:成功响应可以包含空正文。在这种情况下,我们回退并使用Response.statusResponse.statusText来填充生成的响应对象。

fetch(url)
  .then(handleResponse)
  .then((responseJson) => {
    // Do something with the response
  })
  .catch((error) => {
    console.log(error)
  });
export const handleResponse = (res) => {
  if (!res.ok) {
    return res
      .text()
      .then(result => JSON.parse(result))
      .then(result => Promise.reject({ status: result.status, message: result.message }));
  }
  return res
    .json()
    .then(result => Promise.resolve(result))
    .catch(() => Promise.resolve({ status: res.status, message: res.statusText }));
};

希望这对我有帮助 抛出错误不起作用

function handleErrors(response) {
  if (!response.ok) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject({
          status: response.status,
          statusText: response.statusText,
        });
      }, 0);
    });
  }
  return response.json();
}
function clickHandler(event) {
  const textInput = input.value;
  let output;
  fetch(`${URL}${encodeURI(textInput)}`)
    .then(handleErrors)
    .then((json) => {
      output = json.contents.translated;
      console.log(output);
      outputDiv.innerHTML = "<p>" + output + "</p>";
    })
    .catch((error) => alert(error.statusText));
}

我只是通过使用其 -ok 属性检查了响应对象的状态,该属性指示每个布尔值的成功响应(状态从 200 - 299)。

$promise.then( function successCallback(response) {  
  console.log(response);
  if (response.ok) { ... }
});