Fetch API error handling

前端 未结 3 712
借酒劲吻你
借酒劲吻你 2021-02-15 15:52

I want to display error message from my API, problem is that I can\'t reach that error if I check for response.ok, it returns Fetch error, not the one from API..

3条回答
  •  温柔的废话
    2021-02-15 16:09

    In order to extract API message from server in case of some error, you have to use the following idiom (which doesn't lie on the surface though), see link

         fetch("http://localhost:8090/test/error", {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        })
            .then(result => {
                //Here body is not ready yet, throw promise
                if (!result.ok) throw result;
                return result.json();
            })
            .then(result => {
                //Successful request processing
                console.log(result);
            }).catch(error => {
                //Here is still promise
                console.log(error);
                error.json().then((body) => {
                    //Here is already the payload from API
                    console.log(body);
                });
            })
    

    Verbose - yes!, but does exactly what is needed.

提交回复
热议问题