-1

I'm sending a request to a backend THAT IS OFFLINE using axios

const backendClient = axios.create({
  baseURL : env
});

The API gets called

export const createExpensesRecord = async (createExpenseRecordCmd) => {
    try {
        await backendClient.post("/api/accounting/expenses", createExpenseRecordCmd)
        return true
    } catch(error) {
        return false
    }
}

The error code should trigger, as the backend is not reachable with Error: Network Error.

function submitAccountingRecord() {
        if(formDataValid()) {
            
            if(createExpensesRecord(cmd)) {
                console.log("SUCCESS")
            } else {
                console.log("FAILED")
            }

            ...
        }
    }

No matter what I do, I always receive SUCCESS. Played around with it for over an hour and couldn't get consistant behaviour. What am I doing wrong?

Be aware that I tried multiple approaches, maybe we can stick to this one than suggestion different options to solve it. It's the most straight forward approach I could think of

---- UPDATE

await function submitAccountingRecord() {
        if(formDataValid()) {
            
            if(await createExpensesRecord(cmd)) {
                console.log("SUCCESS")
            } else {
                console.log("FAILED")
            }

            ...
        }
    }
nykon
  • 504
  • 4
  • 18
  • `if(createExpensesRecord(cmd))` will always take the "true" branch, because `createExpensesRecord` returns a *promise* (like all `async` functions do), and promises are truthy. The flag is the fulfillment value of the promise. See the linked question for how to get the fulfillment value of the promise (note that it will also be asynchronous). – T.J. Crowder Oct 24 '21 at 15:08
  • I updated a section. I'd expect this to work then, but it doesn't. Changing calling function to async, calling await ... within the if. – nykon Oct 24 '21 at 15:12

1 Answers1

1

Server being offline is not an error really. In fact, you shouldn't rely on any HTTP tool (be it axios or native fetch API). Read this thread to learn more.

msrumon
  • 1,250
  • 1
  • 10
  • 27
  • Thank you your reply. I've been there, that's why I wrapped my axios call in a try-catch. Axios is not returning anything (as there's no server response) so I expect the try-catch to catch the `Network error` – nykon Oct 24 '21 at 15:15
  • As said, **axios** can't detect server offline status. At most, you may get a timeout error (`ECONNABORTED`), which you may want to [look into](https://stackoverflow.com/q/50619928). It may be *hit-and-miss*, so don't solely rely on that. – msrumon Oct 24 '21 at 15:20