Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

116
Views
Promise rejection not being caught by .catch()

I'm having some issues with a large JS application I've been working on for a while. We required a centralised location for throwing various errors from the API. I had a bit of a brainwave and decided a good approach would be to proxy all API calls through a function in the parent API service class.

So I re-wrote all the API calls in my stores to utilise this new method of calling the API, but now some requests aren't throwing the correct errors anymore.

I'm wondering if there are just too many nested promises or something, as the we're using generated code for the API client on the frontend app. So in the example below, the return of anAsyncApiCallHere would be a promise.

I've found circumstances to trigger a 422 from our API for a request but for some reason, I just can't get the .catch in my store to trigger when reject(err) happens.

Here's some example code I scratched together to explain it better:

    // API Service code:

    const ApiService = {
        callApi(module, request, ...args) {
            return new Promise(resolve, reject) {
                this[module][request].call(null, ...args).then(response => {
                    resolve(response);
                }).catch(err => {
                    // I do my extra logic/centralised error message stuff here based on response code
                    // ^ this works
                    // the reject line below does not seem to work
                    reject(err);
                });
            }
        },

        moduleA: {
            requestA(argumentOne, argumentTwo) {
                return anAsyncApiCallHere(argumentOne, argumentTwo);
            }
        }
    }

    // in store:

    export default const StoreModule = {
        actions: {
            makeAnApiCall() {
                let argumentOne, argumentTwo;
                ApiService.callApi('moduleA', 'requestA', argumentOne, argumentTwo).then(response => {
                    // This section works.
                    console.log(response);
                }).catch(err => {
                    // This section isn't working.
                    console.error(err);
                });
            }
        }
    }
7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs