Angular: Built-in solution for managing unhandled HTTP errors

I have implemented a default handler for handling http errors in my angularjs app as shown below:

myapp.config([ '$httpProvider', function($httpProvider) {
    $httpProvider.responseInterceptors.push('errorInterceptor')
}])

The errorInterceptor service is responsible for displaying error details in an alert field located at the top of the current page.

However, when I need to handle a specific error differently (for example, when the query is executed within a modal and I only want to display the alert in that modal), I do this:

$http.get('/my/request').then(success, specificErrorHandling)

Even though the specificErrorHandling function is triggered, the errorInterceptor is still activated, resulting in the error being reported twice. Is there a way to prevent this from happening?

More importantly, is there an Angular method to handle errors that have not been dealt with along the promise chain, similar to how exceptions are handled by the top-level error handler in a server application without having to catch them?

Edit: Here is the code for the interceptor as requested by Beetroot-Beetroot in the comments:

@app.factory 'errorInterceptor', [ '$q', 'alertsHandler',
  ($q, alertsHandler) ->
    success = (response) ->
      response

    failure = (response) ->
        alertsHandler.raise(response)

    (promise) ->
      promise.then success, failure
]

Answer №1

We do have a similar setup in place.

When dealing with http errors, we include a property on the request named errorHandled:true

$http({
    method: 'GET',
    url: '/my/url',
    errorHandled:true
}).then(function(){ ... }, function(){ ... });

In the interception for

responseError: function(rejection){ ... }
, we check if this flag is set by examining rejection.config.errorHandled. If it's not set, we display an error toastr dialog. Here's a snippet of the code:

function ( rejection ) { 
    if ( !rejection.config.errorHandled && rejection.data.message ){
        toastr.error(rejection.data.message, 'Error');
    }
    return $q.reject(rejection); 
} 

The likelihood of someone mistakenly omitting the "errorHandled:true" while including an error handler is quite low. While having two error indicators may seem redundant, it can be beneficial as one is better than none.

It would have been convenient if we could query the promise within the then chain to determine if it has an error handler, but unfortunately, we haven't found a way to do so yet.

Answer №2

Knowing exactly which errors should be suppressed and which ones should be propagated is crucial. Additionally, since the Response interceptor is essentially a function that returns a promise in itself.

In cases of failure, rather than allowing the error to propagate up the stack, you have the option to catch the response and return something like an empty response instead.

For reference, take a look at the example provided in the Angular documentation for interceptors:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return function(promise) {
        return promise.then(function(response) {
            // Handle success
        }, function(response) {
            // Handle error
            if (canRecover(response)) {
                return responseOrNewPromise; // Suppress the error here.
            }
            return $q.reject(response); // Propagate the error.
        });
    }
});

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 functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Having trouble accessing PDF files on Electron framework

Despite following the advice provided in similar questions' answers, such as including webPreferences: { plugins: true } in the options when creating a BrowserWindow instance, I am still encountering issues. Every attempt to open or view a PDF ...

Automating the movement of a slider input gradually throughout a specified duration

I am working on a website that includes a range input setup like this: <input type="range" min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/> Additionally, I have integrated some D3 code for visualizations. You can view ...

What is the best way to make changes to elements in an express array?

I have been developing an express application that enables users to manage a list of web projects through various HTTP methods such as get, post, put, and delete. So far, I have successfully implemented the logic for handling get, delete, and post reques ...

Header and Footer Components in ReactJS

My goal is to design a unique Layout component that will display the Header and Footer. This way, I can later use the Layout like <Layout> ... </Layout> In order to achieve this, I have utilized Routing in both the Header and Footer. To imple ...

Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreci ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

Utilizing Bootstrap 5: Executing JavaScript exclusively upon successful form validation

I've created a form with multiple input fields that are being validated using Bootstrap 5 validation. <form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate> ...

Tips for updating the checkbox state while iterating through the state data

In my component, I have the ability to select multiple checkboxes. When a checkbox is selected, a corresponding chip is generated to visually represent the selection. Each chip has a remove handler that should unselect the checkbox it represents. However, ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

E/launcher - The operation ended with a 199 error code

Hey there, I am new to Angular and Protractor. I keep receiving the error message "E/launcher - Process exited with error code 199" in my code. // conf.js exports.config = { //seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['spec.j ...

Tips for generating an HTML template as a string using jQuery

I have developed a dynamic modal using plain JavaScript, triggered by a button click. This modal is controlled based on the attributes `data-open-hours` and `data-closed-hours` in the HTML. If you take a look at my demo, you will notice an issue. Let me e ...

Using Javascript to save basic high scores to a server

My JS game involves updating a score variable. When the game reaches a gameOver state, I want to compare the score to one saved on the server. If the player got a higher score, I'd like to overwrite the previous high score with the new one. If it&apos ...

While observing a camera in motion, the particles tinted by texture display sporadic flickering on WebGL and Three.js

Check out this jsfiddle I created to illustrate an issue with particles "flickering" when colored using a texture and the camera is moving. Update: The problem occurs even when there is no animation or movement on the particles. If you notice flickering o ...

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

Alter the Cascading Style Sheets (CSS) value by accessing a

I have two files, keyboard.css and keyboard.js. My objective is to modify a CSS rule: .ui-keyboard div { font-size: 1.1em; } Is there an alternative method to change the font size without utilizing $(".ui-keyboard div").css()? I want the modification ...

When attempting to use the POST method with a JSON body in Postgresql, I encounter an error

Encountering an error: There seems to be an issue with a JSON token at position 197 while trying to parse it. It occurs in the following code snippet: at JSON.parse () at parse (C:\Users\hp\empServers\node_modules\body-parser&bso ...