Why am I catching a rejected Promise in a try/catch instead of the Error the Promise was rejected with?

110 Views Asked by At

Javascript in a webbrowser.

There is an async event handler. Inside this event handler a try/catch is used. Inside the try block an asynchoronous functions is called synchronously with await.

Inside the catch block the caught data should be processed. But instead of the error, it catches a rejected Promise with PromiseState: 'fullfilled' and the error it was rejected with as PromiseResult.

Code:

try {
    $(document).ready( async function handleEvent( event ) {
        try {
            //async function called synchronously
            await doSomethingAsync( event );
        } catch( xcp ) {
            //xcp is of type Promise
            //console output shows that it is a Promise with PromiseState: 'fullfilled'
            //and the Error as `PromiseResult`
            console.error( xcp );
        }
    });
} catch( xcp ) {
    console.error( xcp );
}

async function processAjaxError ( jqXHR, textStatus, errorThrown ) {
    let error = new Error ( "textStatus: "+textStatus+", errorThrown: "+errorThrown );
    return error;
}

async function doSomethingAsync( event ) {
    //using a Promise as return type
    return new Promise( function( resolve, reject ) {
        let ServerCall = {
            url: "example.com",
            type: "POST",
            data: {},
            dataType: 'json',
            success: function( data, textStatus, jqXHR ) {
                //success -> let the promise resolve
                resolve( data, textStatus, jqXHR );
            },
            error: function( jqXHR, textStatus, errorThrown ) {
                //failure -> let the promise reject
                let error = processAjaxError( ...arguments );
                reject( error );
            },
        }
        $.ajax( ServerCall );
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

Why am I catching the rejected Promise instead of the Error the Promise was rejected with?

0

There are 0 best solutions below