Vue-resource: catch "Uncaught (in prom)" when catching ajax error

I am using vue-resource

to fetch data from server. The user must have a JWT token to receive correct data. If the token is invalid or expired, a 401 status is returned. If the user tries to access a forbidden page, a 403 is returned.

I would like to catch these errors and handle them appropriately (globally). This means that the calls must be fully handled by the interceptor (if 401, 403).

How can I prevent the browser from displaying "Impossible (in promise)" and create some global error handling? I don't want to have a local error handler on every call.

I have the following interceptor:

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.');
        }
    });
});

      

And the next call in Vue methods

:

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

      

+5


source to share


1 answer


It's a bit of a dilemma, isn't it? You don't want unhandled promise rejections to be swallowed because that means your application might not work and you won't know why and you never get an error.

On the other hand, it's silly to use the same error handling mechanism for every single one .catch()

in your application, so implementing a global error handler is definitely the right way to go.

The problem is that in most cases you will have to rethrow the error from your global error handler, because otherwise your application will think that the request was ok and continue processing the data that is not there.

But this leads to a situation where an error is thrown Uncaught (in promise)

, because the browser will think that you did not handle the error, when in reality you did it in your global error handler.



To get around this there is now an event , and you can use it to prevent the browser from logging these errors, but then you need to make sure you handle them yourself. onunhandledrejection

onunhandledrejection

Therefore, we often have our own error classes, and when a response error is thrown, we convert the error to one of our error classes, depending on the HTTP status code.

We also add a property to this error, for example ignoreUnhandledRejection

and set the value true

. Then you can use a global handler to filter out these errors and ignore them because you know you've already handled them globally:

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

      

0


source







All Articles