Can a promise in JavaScript be assigned a default errorCallback?

Is it possible to set a default errorCallback for a promise in such a way that the default callback is not triggered if the user has provided their own errorCallback?

function getFoo() {
    // TODO implement logic to define defaultErrorCallback as default
    return $http.get("/not_exists");
};

function defaultErrorCallback() { console.log("DDD"); }
function customCallback() { console.log("CCC"); }

getFoo().then(fooSuccess);
// result: DDD

getFoo().then(fooSuccess, customCallback);
// result: CCC

Answer №1

Within HTML 5.1, there exists a feature known as the "uncaught promise rejection" mechanism. This mechanism triggers an "uncaughtrejection" event for promises that are rejected without any handlers in place at the time of rejection. By listening for this event, you can respond to and handle the rejection accordingly. Additionally, monitoring "rejectionhandled" events can provide further insights into the process. Essentially, implementing your own HostPromiseRejectionTracker, as described in section 25.4.1.9 of the ES7 standard (page 521 of the pdf), can become quite intricate rather quickly.

In traditional Promise implementations, users must explicitly add handlers for promise rejections, either through the second parameter of .then or the first parameter of .catch (which essentially serves as shorthand for the then method). While there are various explicit ways to handle rejections, there is no built-in option to supply a default rejection handler that will be automatically invoked if a user fails to specify one.

It's worth noting that support for "uncaughtrejection" events is not yet widespread across browsers, and the specification itself may undergo revisions before seeing widespread adoption.

Answer №2

There doesn't seem to be a direct way to handle errors for individual promises, but you can customize Angular's default error handling behavior by overriding it. This allows you to specify how errors should be handled, especially those that are not caught elsewhere in Angular:

angular.
  module('customErrorHandler', []).
  factory('$exceptionHandler', ['alertService', function(alertService) {
    return function myExceptionHandler(exception, cause) {
      alertService.alertError(exception, cause);
    };
  }]);

If you specifically need to handle errors from a particular function like getFoo(), you can modify the error object to include identifying information:

function getFoo() {
    return $http.get("/not_exists")
        .catch(function (error) {
            error.errorSource = 'getFoo';
            throw error;
        });
}

// somewhere else...
angular.
  module('customErrorHandler', []).
  factory('$exceptionHandler', ['alertService', function(alertService) {
    return function myExceptionHandler(exception, cause) {
      if(exception.errorSource === 'getFoo') {
        alertService.alertError(exception, cause);
      } else {
        // default error handling
      }
    };
  }]);

Answer №3

Consider wrapping the code like this -

Keep in mind that a promise is an object that can be chained.

function defaultCallback(){}
function okCallBack(){}
function getFoo(successCallback) {
    // Insert your $q logic here.
    var firstPromise = $http.get("/foo");
    var defaulErrorCallback=defaultCallback;
        if (typeof successCallback == 'function') {
          return firstPromise.then(successCallback).catch(defaulErrorCallback);

      }else{
         return firstPromise; 
      }
    };
getFoo(okCallBack);

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

Importing JavaScript into an Angular component: A beginner's guide

Within my Angular-11 project, I have included the following JavaScript file: "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js", I have added it to the angular.json configuration as detailed above. import Stepper from '.. ...

Step-by-step guide to designing a custom eBay-inspired logo page using HTML and CSS

Recently, I stumbled upon a fascinating website design for eBay's new logo page. It got me thinking about how I could recreate something similar for my own website. The concept of having the logo visible through the gaps is quite intriguing. If you&a ...

What techniques can I use to streamline this jQuery script?

Presented below is the code for a straightforward newsletter signup widget. I believe there's potential to streamline it further, any suggestions? const emailForm = $('.widget_subscribe form'); const emailSubmit = $('.widget_subscrib ...

Is it possible to use regex for matching both spaces and letters exclusively?

I recently created a regular expression that only allows letters. While I'm not very experienced with regex, I am struggling to figure out how to also include spaces in my expression. This is the HTML code I have: <input id="input" /> Below i ...

jQuery Mobile: smooth page transitions on desktop, but issues on Android phones

$('div.ui-page').live("swipeleft", function () { var nextpage = $(this).next('div[data-role="page"]'); if (nextpage.length > 0) { $.mobile.changePage( nextpage, {transition: "slide"}, ...

Using ReactJS to create cross-browser inline styling with flexbox

I'm currently working on a React web application that relies heavily on inline styling. My goal is to ensure compatibility with the latest versions of major browsers (Safari, Chrome, Firefox, IE) while utilizing flexbox for layout. The issue I encou ...

Why isn't the import statement fetching the necessary function for me?

Hello, I am currently utilizing NextAuth for my application: The main file I am attempting to pull data into: [...nextauth].js import NextAuth from "next-auth" import Providers from "next-auth/providers" export default NextAuth({ // ...

The process of reversing an array is not fully completing due to the pop method being used within a loop

Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question. I want to create a basic functi ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

Dynamic parameters in the Vue router

Struggling to find the right syntax for passing dynamic param data. Experimented with multiple approaches, but I thought I could pass someValue like this: <router-link :to="{ name: 'Foo', params:{ bar: ${someValue} } }"> Unfortunately, co ...

Can the identical script be implemented by utilizing two separate JavaScript files?

My knowledge of JavaScript is limited, so I often rely on resources like JavaScript.com and Dynamic Drive for coding. Recently, I came across some scripts that reference two different .js files. <script type="text/javascript" src="lib/prototype.js"> ...

increase the count by one every second using setInterval

I need my sHand to increase by 6 every second, but currently it only increases once. When I try something like this.sHand++, it works fine and increases by 1 degree per second. However, I want it to increase by 6 instead of 1. Any solutions? data:{ ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

Utilizing AngularJS directives with the power of string formatting

Looking at this JSON structure {textTemplate:"Name:{0},Phone:{1}",controls:[{id:1,Name:"Name",type:"text"},{id:2,Name:"Phone",type:"text"}]} I'm unsure how to utilize the directive for converting strings into HTML controls This is what I&apos ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...

The script is not having an impact on the element that was just created

Recently, I developed two scripts to manage a list. One script adds an li element on the page and saves it to the database, while the other removes it. However, I encountered an issue where the second script fails to remove the newly added li element witho ...

The concept of promises and futures in JavaScript bears a resemblance to the functionality present

Is there a JavaScript library that offers promises and futures with syntax similar to C++? We need to use them in webworkers without a callback interface. I want the webworker to pause on a future and resume when the UI thread assigns a value to it. I ha ...

Guide to dynamically assigning v-on with v-for

I'm working on a Vue code that dynamically creates a menu using v-for, with each element requiring a different method when clicked. Here's what I have so far: <span v-for="(menuItem, index) in menuItems" :key="index"> ...

Challenges arise when trying to maintain a div aligned to the far right of the browser window as the dimensions of the browser change, especially after applying an

I have a main container div that holds two smaller divs side by side. When one of these smaller divs is clicked, it moves to the far left or right side of the browser window depending on which one was clicked. This functionality works perfectly as intended ...