Using vue-resource to intercept an ajax error and catching the "Uncaught (in promise)" exception

I am utilizing vue-resource to retrieve data from the server. In order to access the correct data, a user must possess a JWT token. If the token is invalid or has expired, a status code of 401 will be returned. Similarly, if a user attempts to reach a forbidden page, a status code of 403 will be returned.

I aim to capture these errors and manage them in a global manner. This implies that any calls should be handled entirely by the interceptor (for 401 and 403 errors).

How can I avoid the browser message "Uncaught (in promise)" and establish a system for global error handling? I prefer not to implement a local error handler for every individual call.

The current interceptor setup:

Vue.http.interceptors.push(function (request, next) {
    request.headers.set('Authorization', Auth.getAuthHeader());

    next(function (response) {
        if (response.status === 401 || response.status === 403) {
            console.log('You are not logged in or do not have the rights to access this site.');
        }
    });
});

Additionally, here is the method within Vue:

methods: {
    user: function () {
        this.$http.get('http://localhost:8080/auth/user').then(function (response) {
            console.log(response);
        });
    }
}

Answer №1

Are you facing a dilemma? Handling unhandled promise rejections can be tricky because it could lead to your application malfunctioning without any explanation, leaving you in the dark about what went wrong.

However, using the same error handling approach for every .catch() statement in your codebase may not be the most efficient solution. Implementing a global error handler seems like the best way forward.

The challenge arises when you realize that you might need to re-throw errors from your global handler. Failure to do so could result in your application assuming everything is fine and proceeding with incomplete data processing.

This situation often triggers the dreaded Uncaught (in promise) error in the browser, even though you've handled the error globally.

One workaround involves leveraging the onunhandledrejection event to prevent these errors from being logged by the browser. However, this means you will have to take on the responsibility of managing these unhandled errors yourself.

A common practice is to define custom error classes and convert response errors into your designated error types based on their HTTP status codes.

In addition, you can include a property like ignoreUnhandledRejection in these errors and set it to true. This allows you to use the global handler to filter out these specific errors and avoid unnecessary logging since you've already addressed them at a higher level:

/**
 * Prevent logging already processed unhandled rejection in console
 */
window.addEventListener('unhandledrejection', event => {
  if (event.reason && event.reason.ignoreUnhandledRejection) {
    event.preventDefault();
  }
});

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

Having trouble loading the DOM element within the child component

An issue has arisen with Angular 4.4.6 regarding the access of a DOM element by ID from a different component. Within my component, I aim to display a Google Maps for specific purposes. Following the examples given in the API, I include the following code ...

Discovering intersection points along a line between the previous and current positions of the mouse in Three.js

I am working on a project in Three.js where I have a scene filled with lines. Everything is working smoothly when the mouse moves slowly, as I am using the raycaster method to check for intersections with the lines. However, the issue arises when the mouse ...

Is there a way to automatically interpret and analyze a gruntfile in order to make changes to it and then resave it?

I'm working on a intricate Yeoman Generator and I'm in search of a solution to parse an existing gruntfile. If anyone knows a JavaScript method for parsing a gruntfile, your assistance would be greatly appreciated. ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

Tips for differentiating between elements with identical values in an HTML datalist using Angular

My boss is insisting that I use a datalist in our website interface to select an employee, even though there's no way to determine if the user typed in the name or picked from the list. The challenge is that the list must only display full names, but ...

Steps for sending data to a modal window

Consider this scenario: I have a function that retrieves some ids, and I utilize the following code to delete the corresponding posts: onClick={() => { Delete(idvalue[i]) }} Nevertheless, I am in need of a modal confirmation before proceeding with the ...

Encountering an unrecognized error on Windows when attempting to execute a child process with regex return

Below is the code I am utilizing to retrieve Make file targets: const command = `make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\\/t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'`; cp.exec(command, options, (error, stdout, s ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Dispatch is successful half of the time in children when looping within useEffect

Recently, I embarked on the journey of learning React. However, I encountered a problem when using dispatch in UseEffect, which is nested inside a child component loop. While I cannot share the entire project, here is a snippet of the code: The home page ...

Incrementing and decrementing a textbox value by one using onClick

I'm looking for help with a JavaScript solution without using jQuery or any plugins, specifically for Cordova/PhoneGap. I am new to JavaScript and learning as I go, so please bear with me. My goal is to create a functionality where there is a textbox ...

Using Typescript to change a JSON array of objects into a string array

I'm currently working with the latest version of Angular 2. My goal is to take a JSON array like this: jsonObject = [ {"name": "Bill Gates"}, {"name": "Max Payne"}, {"name": "Trump"}, {"name": "Obama"} ]; and convert it into a st ...

How to categorize an array of objects based on a specific property while preserving the original object attributes

I have an array of objects with a specific property that I want to group by. My objective is to create a new array where all the objects have the same properties, but with an additional property that combines all the "value" properties into an array. Here ...

I am experiencing an issue where the custom form validation directive in AngularJS is not functioning properly within my modal

To enhance the validation of my input boxes, I created a custom directive called nx-validate. This directive is designed to be added to a bootstrap div.form-group, which will then check if the <input/> field is $dirty or $invalid, and apply the appro ...

Error retrieving data from JSON

I'm attempting to extract a value from the JSON data retrieved via Ajax. Take a look at the example I'm working on here: http://jsfiddle.net/NNrcp/6/. jQuery.ajax({ url:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.pla ...

Incorporate a `fresh Audio` element into my redux repository

I'm attempting to include a new Audio element in my redux store. This is how my reducer appears: export const songsReducer = (state = {}, action) => { switch (action.type) { case "PLAY_SONG": return { ...state ...

Navigating the From and To routes in Nuxt/Vue: A comprehensive guide

I am currently working on a Nuxt/Vue project. While inspecting in Dev Tools, I came across a From and To property. How can I access these properties within the Nuxt application? I have attempted to use this.$nuxt.$route, this.$nuxt.$router, and this.$rou ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Bringing joy to a JS library: Embracing both Node and the Window

I have developed a JS library that I want to convert into a Node module for use with Node.js. This library extends the Canvas context API and relies on the use of getImageData(). Therefore, it begins with a defensive check to ensure compatibility: if (wi ...