What is the best way to handle errors that occur asynchronously without using promises in order to respond to those specific errors?

I have searched for answers but none seem to directly address my specific question.

My current usage involves the pattern shown below:

 class A
 {
     getLocation()
     {
         return Promise.reject(2222222)
     }
     async a()
     {
         try
         {
             var loc = await this.getLocation();
             alert(loc)
         }
         catch (e)
         {
             alert("catch 2")
         }
     }
 }
 new A().a();
  • Result : "catch 2"

Even when I introduce an error in the getLocation function :

  getLocation()
     {
         throw Error("ffffff")
     }

- I still get the same result - which is expected.

But here lies the issue:

The behavior of errors thrown asynchronously-non-promised is different:

So this code won't be caught at all:

  getLocation() //bad code from a third party code , third party code
  { 
      return new Promise((v, x) => setTimeout(() =>
      {
          throw Error("ffffff")
      }, 100))
  }

Question:

Considering that I want to capture these errors, is there a better approach?

I could simply do:

window.onerror = function () { alert(4)}

However, this would not align with the flow of .catch(...) or catch(){}, and I wouldn't be able to handle actions specifically related to the error-causing event.

Full disclosure:
This scenario is purely for educational purposes.

Answer №1

an issue that arises asynchronously without promises can be quite tricky to handle

Avoiding this issue is crucial and should be a top priority. It's important to never include business logic (even simple tasks like accessing properties) within asynchronous non-promise callbacks as it can potentially lead to errors. For example, keep in mind that functions like `JSON.parse` can fail, trying to access a property on `null` or `undefined` can throw an error, or a loop may fail if the object being iterated is not an array with a `.length` property.

The only acceptable operations within asynchronous non-promise callbacks are `resolve`, `reject`, and possibly a function like `(err, res) => { if (err) reject(err); else resolve(res); }` for APIs with multiple arguments.

To address this issue, you can refactor problematic code snippets like:

async getLocation() {
    await new Promise(resolve => setTimeout(resolve, 100));
    throw Error("ffffff");
}

or

getLocation() {
    return new Promise(resolve => setTimeout(resolve, 100)).then(res => {
        throw Error("ffffff");
    });
}

If the faulty code belongs to a third-party library, try contacting them to fix it, submit a merge request with your solution, or consider switching to another option altogether.

Is there a more effective approach to handling this situation?

While domains in Node.js were initially introduced to address issues with uncaught asynchronous exceptions, they ultimately proved unsuccessful. Perhaps in the future, technologies like zones, which offer better support at a language level, could provide a more robust solution.

Answer №2

Errors need to be captured at the exact location where they originate.

The following code snippet is flawed and requires fixing directly in the code:

getLocation() // This is bad practice from a third-party source
{ 
    return new Promise((resolve, reject) => setTimeout(() =>
    {
        throw Error("ffffff")
    }, 100))
}

If this is third-party code, it can either be forked or patched for improvement.

To globally monitor exceptions, developers can utilize the onerror method as mentioned earlier. It should solely serve as a notification tool for existing errors rather than being used to handle them conventionally.

The unhandledrejection event also serves the same purpose of notifying about unhandled promise rejections. However, it may not address errors within the given snippet since they are thrown within a setTimeout callback and do not lead to promise rejection.

Answer №3

Here is an example of how the basic usage would look:

class A {
  getLocation(x) {
    return new Promise((resolve, reject) => setTimeout(() => {
      // a lot of asynchronous code
      try {
        //simulating unexpected exception    
        if (x === 2) {
          throw ("code error");
        }
        if (x) {
          resolve('success');
        } else {
          reject('conditional rejection');
        }
      } catch (ex) {
        reject(ex);
      }
    }, 1000));
  }
  async a(x) {
    await this.getLocation(x).then((loc) => console.info(loc)).catch((e) => console.error(e));
  }
}
let o = new A();
o.a(2);
o.a(0);
o.a(1);

The rejection of the Promise doesn't always mean there is a code Exception, and similarly, a code Exception doesn't necessarily lead to a Promise rejection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function cannot be called on params.getValue()

I am facing an issue while trying to retrieve the value of a specific row's column ID. The goal is to change the URL by appending the retrieved ID when clicking on an icon. However, I encountered an error stating TypeError: params.getValue is not a fu ...

Guide on adding JSON data from a web service whenever a function is invoked in AngularJS

I am currently calling the getData function every second and everything is working fine except for the appending functionality. Whenever the function is called, AngularJS replaces the old data with new data, but I actually want to append the new data aft ...

Ways to effectively test public functions in Typescript when using react-testing-library

I have come across the following issue in my project setup. Whenever I extend the httpService and use 'this.instance' in any service, an error occurs. On the other hand, if I use axios.get directly without any interceptors in my service files, i ...

Is there a way to display the inbox area upon completion of the document loading process?

I'm currently working on creating an inbox feature for my personal portfolio, mostly as a learning exercise rather than for any practical use. However, I've run into an issue where all emails are being displayed by default when the page loads wit ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Learn the process of showcasing database content on a webpage with an interactive feature that enables users to choose and access additional details

Apologies if this question has been asked before, I have searched for a solution but my web development knowledge is limited. To better understand my issue, you can visit the site at 000freewebhost by following this link: In summary, I am trying to select ...

Error: Attempting to access the text content of a null object

I recently followed a tutorial on text reveal animation and attempted to implement it in Next.Js. Unfortunately, I encountered an error message stating "TypeError: Cannot read properties of null (reading 'textContent')". Here is the video tutori ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

JavaScript - The function will not execute any code inside its body

When I try to call my constructor function, it stops at the function definition in the debugger and never reaches the actual function body. Is there a common reason for this issue that I might be missing? Here is an example of the code: myconstructor.js ...

Using Jquery to insert a line break in a textarea: instead of using , use ↵

I've encountered an issue while attempting to retrieve the value of a textarea with line breaks using jQuery. Upon debugging, I noticed that the value is stored in a variable which looks like this: "test<br> test<br> test"<br> In th ...

What could be causing the JWT token to not be transferred to the backend API when the page is reloaded or loaded?

In my user context, I encapsulate all components: const UserContext = ({ children }: AccountContextProviderProps) => { const [user, setUser] = useState({user: "", loggedIn: false}); const navigate = useNavigate(); useEffect(() => { ...

Setting the Content-Type of a JavaScript file within a NodeJS application

I am facing an issue with opening a js-file on my NodeJS server, as it always specifies the .js file with a Content-Type of "text/html." My objective is to send user-input from an html form to a JavaScript file for performing calculations and later genera ...

Preventing me from instantiating objects

I've been struggling with an issue for a while now consider the following: export abstract class abstractClass { abstract thing(): string } export class c1 extends abstractClass { thing(): string { return "hello" } } export cla ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Tips on redirecting the user to the page they have selected

<section> <div class="container"> <select name="semester" id="select-semester"> <option value="no-semester">choose a semester</option> <option valu ...

Dynamic updating of Laravel models

I am facing an issue with my website where a series of posts are displayed upon loading, sent to the page using a controller in the following return statement: return View::make('stream')->with($this->postStream()); The postStream functio ...

What are the steps for enlarging the display containing components with the 'position: absolute' style?

How can I magnify the screen with the following code? .drawing-board { width: 25%; height: 25%; background-color: black; position: relative; /* transform: scale(2, 2); */ } .drawing-board .box-1 { width: 20px; height: 20px; background-c ...

Exploring the extraction of elements from list items using jQuery

Can you help me with removing the anchor tag from the list item? This is the current markup: <ul class="yith-wcan-list yith-wcan "> <li><a href="#">Item 1</a> <small class="count">8</small> <div class="c ...

How can I determine the quantity of pairs in an array using JavaScript?

My current approach is not providing me with the desired result. I am facing an issue where pairs of 1 are being counted multiple times, which is incorrect. What I actually need is to count only the "perfect" pairs, such as the pair between 5 and 2 in this ...

What is the reason behind `tslint` flagging `TS2531: Object may be null` even though I verified its existence beforehand?

In my React project, I am utilizing typescript. The following code snippet is part of my typescript implementation: if(this.state.deletedItem !== null) { this.props.deleteItem({refItemIdx: this.state.deletedItem.itemIdx}); } ...