Handling Uncaught (in promise) Error in Frontend JavaScript

KASATA - TechVoyager
2 min readApr 17, 2024

--

JavaScript is a fully-fledged language that allows us to write interactive codes that can handle real-time scenarios. One common real-time scenario is handling errors. More often than not, JavaScript developers encounter an error: Uncaught (in promise) Error. This error typically happens when a promise is rejected, but there is no error handler to catch it.

Root Cause of “Uncaught (in promise) Error”

The root cause of this error is typically due to unattended Promise rejection. When a Promise is rejected and no error handler is provided to catch it, browsers’ console will log “Uncaught (in promise) Error”.

Handling “Uncaught (in promise) Error”

There are generally two ways to handle this error: using `catch()` or `finally()`.

Using `catch()`

The `catch()` function serves as an error handler that catches any error that occurs in the Promise.

Here is a sample code:

```javascript new Promise((resolve, reject) => { throw new Error(“Error!”); }).catch(err => console.log(err)); // This will log: Error: Error! ```

In the example above, `catch()` function catches the error thrown in the Promise.

Using `finally()`

The `finally()` function will always run when the Promise is settled, whether it fulfills or rejects.

Here is a sample code:

```javascript new Promise((resolve, reject) => { throw new Error(“Error!”); }).finally(() => console.log(‘Promise settled’)); // This will log: Promise settled ```

In the example above, `finally()` function runs irrespective of the outcome of the Promise.

To Conclude

It is very essential to handle “Uncaught (in promise) Error” to ensure our JavaScript code is robust and error-free. By correctly implementing error handlers, such as `catch()` or `finally()`, you can avoid unexpected crashes and provide a great user experience.

Remember, a good developer is one who writes a code that not only works but also handles unexpected errors gracefully.

--

--

KASATA - TechVoyager

Master of Applied Physics/Programmer/Optics/Condensed Matter Physics/Quantum Mechanics/AI/IoT/Python/C,C++/Swift/WEB/Cloud/VBA