Try catch not working even when error is occuring

时间:2019-04-17 00:58:58

标签: javascript reactjs try-catch

I have some code which executes on the submission of a form. It posts to an API route.

  handleSubmit = async () => {
    try {
      const response = await fetch(`${API_URL}/project`, {
        method: "post",
        body: JSON.stringify({
          name: this.state.name,
          description: this.state.description
        }),
        headers: { "Content-Type": "application/json" }
      });
      return response ? response.json() : response;
    } catch (error) {
       console.log(error)
    }
  };

The problem is when testing this I change the API route to a deliberately invalid route in order to cause an error. However the catch code is not getting hit. Have I setup the try-catch wrong?

3 个答案:

答案 0 :(得分:1)

The issue you are facing is that receiving a 404 is not an exception. To handle this, you should add some code that will check the status code of the response and from there determine what should be done. For example you would receive the response and use the following:

if(response.status == 404)
    //Code for not receiving the content you expect

The issue is there are a lot of potential responses you may get back that will not be what you are looking for, so I would actually recommend whitelisting particular response ranges instead of looking for ones that are a problem. For example

if(response.status >= 200 && response.status <= 299)
    //Code to run when you receieve a good response

This is an example, it will be up to you to determine what are the responses you wish to handle.

答案 1 :(得分:0)

fetch only raises an error if there was an error making or receiving the response. A HTTP 404 should be treated as a "successful" response and is up to the user to decide what to do with such response.

If you want to reject non-20x responses and you already have a business logic to handle error on your catch code, you can throw a new Error and handle it alongside another errors:

try {
    const response = await fetch(`${API_URL}/project`, {
    ...
    if (response.status >= 200 && response.status < 300) {
        return response.json()
    } else {
        var error = new Error(response.statusText || response.status)
        error.response = response
        throw(error)
    }
} catch (error) {
   console.log(error)
}

答案 2 :(得分:0)

如果您需要获取特定的错误,则必须按照以下方式操作:

handleSubmit = () => {
    fetch(`${API_URL}/project`, {
        method: "post",
        body: JSON.stringify({
            name: this.state.name,
            description: this.state.description
        }),
        headers: { "Content-Type": "application/json" }
    }).then((response) => {
        return response ? response.json() : response;
    }).catch((error) => {
        console.log(`fetch specific error: ${error}`)
    });
};
相关问题