How to use returned JSON error in a JavaScript async fetch call

前端 未结 2 1820
粉色の甜心
粉色の甜心 2021-01-27 07:55

I have an async fetch call which calls my backend to create a customer with an email address. If successful, the JSON returned is sent to a doNex

相关标签:
2条回答
  • 2021-01-27 08:11

    Personally I recommend the async/await syntax if the version you're using supports it. It really simplifies the code and allows you to easily use the try/catch syntax.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Browser_compatibility

    It seems it doesn't work in IE though if that's a dealbreaker.

    async function createCustomer(email) {
    try {
        const response = await fetch("/api/create-customer", {
            method: "post",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email: email })
        })
        if (response.ok) {
            const returnedData = await response.json();
            // if doNextThing is an async function, you can await it as well or just return it 
            doNextThing(returnedData);
        } else {
            throw {
                json: await response.json()
                status: response.status,
                statusText: response.statusText
            };
        }
    } catch (requestErr) {
        // do what you like with the error
        // this will be called if you "throw" above or 
        // if fetch() rejects
        if (requestErr.json){
            console.error(JSON.stringify(requestErr.json));
        }
        console.error("Request err:" + requestErr);
    }
    

    }

    Let me know if that helps.

    0 讨论(0)
  • 2021-01-27 08:13

    You should be able to get the content using response.json() in the catch handler.

    0 讨论(0)
提交回复
热议问题