Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise?

function testError() {
    throw new Error("new error") // How can this error be properly handled?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

testError().catch(err => {
        return err;  // The execution does not reach here
    })
    .then(ok => {
        console.log(ok)
    });

Answer №1

If you're uncertain about whether a function will throw an error (or return a value) synchronously, you have the option to call it using .then(). This approach will encapsulate the function in a way that ensures consistent handling of the result regardless of how it is generated:

function testError() {
  throw new Error("new error") // how should this be managed?
  var p123 = new Promise(function(resolve, reject) {
    resolve(123)
  });
  return p123
};

Promise.resolve()
  .then(testError)
  .catch(err => {
    console.error(err);
    return err; 
  })
  .then(ok => {
    console.log(ok.message)
  });

Answer №2

When encountering an error that does not involve async code, it is sufficient to use a traditional try-catch block like the one below:

try {
  testError().catch(err => {
    return err;  // this code won't execute
  })
  .then(ok => {
     console.log(ok)
  });
}
catch(e) {
   // 
}

It's worth noting that as soon as the async-await pattern becomes the primary method for handling promises, the try-catch structure will also become the standard way of managing errors:

try {
    var ok = await testError();
    console.log(ok)
}
catch(e) {
    console.log('e:' + e);
}

This approach effectively deals with both synchronous and asynchronous errors, offering a much cleaner solution compared to using then-catch.

Answer №3

If possible, modify your testError function in this manner

function testError () {
  return new Promise(function (resolve, reject) {
     throw new Error('new error')
     resolve(123)
  })
}

testError().then(ok => console.log(ok),
                 err => console.error(err.message))

  1. Execute it once to observe the error being thrown in console.error
  2. Disable the throw line to witness the promise resolving successfully

Answer №4

When errors occur outside of promises, they cannot be caught using promise catch statements.

One alternative is to use a try/catch block to handle the error instead.

function testFunction() {
    throw new Error("A new error has occurred") // How can we deal with this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

try {
  testFunction().then(result => {
    console.log(result)
  });
} catch (error) {
  console.log(error.message);
}

Answer №5

You should consider rewriting it, as having a caller check for both exceptions and rejections is not a recommended practice:

function handleErrors() {
  return Promise.resolve().then(() => {
    throw new Error("new error"); // this will reject the promise
    return new Promise(function(resolve) {
      resolve(123);
    });
  });
}

handleErrors().catch(err => console.log("Caught " + err));

This behavior is inherent in async functions as they always return a promise:

async function handleErrors() {
  throw new Error("new error"); // this will implicitly reject the promise
  return await new Promise(function(resolve) {
    resolve(123);
  });
}

handleErrors().catch(err => console.log("Caught " + err));

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

A step-by-step guide on how to fill a Vuetify select box with data retrieved from

I'm currently working on populating a select box in Vuetify by retrieving data through an ajax call. I'm struggling to figure out how to populate the select box with this data. The ajax call is successful and I receive an array of objects which I ...

Is the value incorrect when using angular's ng-repeat?

Currently iterating through an array nested within an array of objects like this: <div ng-repeat="benefit in oe.oeBenefits"> <div class="oeInfo" style="clear: both;"> <div class="col-md-2 oeCol"> <img style="he ...

Modify the contents of an array within a string using JavaScript

let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com"; let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"]; I'm trying to replace all URLs in the 'message' array with "***" from the 'ur ...

Iterate through a JavaScript grid and display the items

I am attempting to iterate through a JavaScript table, aiming to display the elements located between two selections made by the user. Here is an example of the table structure: if the user selects IDs 2 and 5, the loop should display rows 3 and 4. I trie ...

Obtain the selected node in FancyTree

When a button is clicked, I need to grab the current node that is in focus. In my attempt to achieve this, I utilized the getFocusNode() method within a click event handler like so: function retrieveFocusedNode() { var currentNode = $("#tree").fancy ...

Tips for displaying a specific array in react JS using the map function

Hello everyone, I am currently working on creating a hotel webpage using React.js and I'm focusing on developing the facilities page. My goal is to display the description of the facilities based on the button that the user clicks. How can I achieve t ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

TS2688 Error: Type definition file for 'tooltip.js' not found

Why am I getting an 'undefined' error when trying to import the Tooltip class from the npm tooltip.js package in my TypeScript file? ...

What modifications can be made to the code in order to show the upload progress for each individual file when uploading multiple files simultaneously?

I am currently working on an uploader that can handle multiple file uploads and displays the progress of each uploaded file. However, I am facing some difficulties in showing the progress of every individual file. Can anyone provide me with assistance? &l ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

What causes the low Performance score of a default NextJS Application with no content?

Just started experimenting with my initial Next.js project. Upon generating a new project using create-next-app, I decided to test its performance with the web application 'Lighthouse'. Surprisingly, although most other metrics scored above 90, ...

The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to ...

What is the best way to ensure that only one accordion tab remains open at a time, preventing it from closing unless a different tab

How can I ensure that only one accordion tab is open at a time, automatically closing any others that are currently open? Here is my current code for the accordion: $('[data-bs-toggle="collapse"]').on('click', function(e) { if ($( ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

What are the steps for performing a self-triggered AJAX post request?

I have been exploring self-invoked functions and recently used an http.get function to retrieve data from a JSON file like this: var Callmodule = (function(){ var urljsonEntrata= "modello.json"; function getmodules(){ var req = $.ajax({ url: ...

prior to activating a state in angular.js, navigate to a distinct controller

Upon loading my website, I have a specific state in mind that I want to be redirected to. Achieving this is made possible through the following code snippet. angularRoutingApp.run(function ($rootScope, $state, $location, $transitions) { $transitions.o ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Display a button within a table depending on the content of adjacent cells

Below is the code snippet I'm currently working with: <tbody *ngIf="packages"> <tr *ngFor="let package of packages"> <td class='checkbox'> <label class="css-control css-co ...