.catch() is catching all errors even from another promise by fetch()

parse

I have created a simple function to authenticate users by their stored tokens, that function is based on a promise which returns a response with user details if it was successfully connected to our server API, if there's a server connection, it will return a promise rejection with specified error by React-native fetch method.

import React, { Component } from 'react';
import {
    Text,
    View,
    AlertIOS,
} from 'react-native';

function AuthAPI(token)
{
    return new Promise((resolve, reject) => {
        fetch("https://myawesomeapi.com/auth", {
            method: "POST",
            body: '{"token": "' + token + '"}',
        })
        .then((response) => response.json())
        .then((response) => {
            resolve(response);
        })
        .catch((error) => {
            reject(error);
        });
    });
}

export default class Home extends Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            bodyMessage: 'Waiting for response!',
        };
    }

    componentWillMount()
    {
        AuthAPI("token-here")
        .then((response) => {
            const justAnotherVar = iamNotExist; // this will throw an error in next .catch
            AlertIOS.alert("Your Name: " + response.userFullName);
            this.setState({bodyMessage: 'Fetch is done with a response!'});
        })
        .catch((error) => {
            console.err(error);
        });
    }

    render()
    {
        const { bodyMessage } = this.state;
        return (
            <View style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
            }}>
                <Text>Welcome..</Text>
                <Text>{bodyMessage}</Text>
            </View>
        );
    }
}

Problem explanation:

When there's an error inside AuthAPI.then(/***/), it will be caught by AuthAPI.catch but as I understand AuthAPI.catch will only catch errors returned by react-native fetch method errors from that promise rejection.

For example, inside AuthAPI.then, I have assigned an undefined variable to a new constant variable const justAnotherVar = iamNotExist; so that will throw an error in the next catch.

ReferenceError: Can't find variable: iamNotExist

What I want is to keep AuthAPI.catch getting fetch method errors only and get regular red screen with specified error when there's an error inside AuthAPI.then(/***/)

Matt Aft

I believe this is intended to happen, read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

What you can do is add a try/catch so the .then statement has it's own error handling and won't trigger the .catch when there's an issue:

  AuthAPI("token-here")
    .then((response) => {
        try {
          const justAnotherVar = iamNotExist; // this will throw an error in next .catch
          AlertIOS.alert("Your Name: " + response.userFullName);
          this.setState({bodyMessage: 'Fetch is done with a response!'});
        } catch (e) {
          //error handling
        }
    })
    .catch((error) => {
        console.err(error);
    });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Promise.catch() not catching errors from promise

Why catch at the end of promise chain is not catching all the errors?

Promise.all() and catching errors

Julia Try Catch statement not catching all errors

Catching promise errors inside another promise's callback

Why Catch is not catching errors?

Catching all errors

Why does Promise.all() throw an exception even if I .catch() it?

Tcl: catch errors from all commands

Not catching exceptions even though it is inside try catch?

try..catch not catching async/await errors

Catching multiple errors in one try/catch

Try - catch() not catching errors and throwing it instead

catch block isn't getting my errors from the fetch api

Catching Errors Inside Promises and Rejecting Promise

async and await and promise in regards to catching errors

Catching errors in Promise, Observable.fromPromise() and subscribtion

JavaScript Promise : Catching errors within chained functions

Catching Errors From Cloudinary In Rails

Catching mysql errors from php

Promises - catching all rejections in a Promise.all

Promise.all error handling — make result of one Promise accessible in another Promise's catch?

Promise.catch is swallowing errors

Catching All Promise Rejections in an Async Function in JavaScript

Catching Errors Inside Multiple .all() Calls

Add to existing Promises.all array from catch of Promise

catch all types of errors from whole application Android

Catch all errors clientside sent from any service

Is "catch(console.error)" a valid way of catching Promise rejections?