'How to handle network errors or cancel post request when using a try/catch block in javascript

I am using AWS services for my app, and got an error I have no idea how to handle or correct it.

When sending a post request using:

  async function _publishPost(){
    try {
      const newPost = {
        name: username,
        id: 12345678,
      };
      await API.graphql(graphqlOperation(createPost, { input: newPost }));
    } catch (e) { console.log(e); }
  }

When running it under low network I get the error:

  //AFTER A FEW SECONDS
  [ERROR] 14:41.398 axios-http-handler - Network Error
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:127:15 in prototype._log
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:210:8 in prototype.error
  at node_modules/@aws-amplify/storage/lib-esm/providers/axios-http-handler.js:178:20 in axios.request.then._catch$argument_0
  
  //AFTER WAITING A FEW MINUTE 
  [ERROR] 17:52.671 axios-http-handler - Request failed with status code 400
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:127:15 in prototype._log
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:210:8 in prototype.error
  at node_modules/@aws-amplify/storage/lib-esm/providers/axios-http-handler.js:178:20 in axios.request.then._catch$argument_0

I expected the error to be logged by the catch block and logged but the errors arent caught by the trycatch. I am not sure how I'd catch the error, cancel the request early enough and not let it freeze the app with a loading screen

I retried uploading it under the same network circumstace and I get the same error. With fair network connection it works perfectly.

*I am using expo to run the app



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source