[Vuejs]-Typescript accusing error when using catch

0👍

  • Exceptions in JavaScript are untyped, and TypeScript cannot use type-checked catch blocks (nor .catch promise methods).
    • Indeed, it’s perfectly valid to do throw null; or throw "Hello, world"; in JavaScript.
    • …and TypeScript code must correctly handle those situations.

…so you need to handle all of those cases in TS. To do this, you’ll need a type-guard function, like so:

interface MyError extends Error {
    readonly response: MyResponse;
}

interface MyResponse {
    readonly data: MyData;
}

interface MyData {
    readonly message: string;
}

function isMyError( x: unknown ): x is MyError {
    
    const whatIf = x as MyError;
    return (
        typeof whatIf?.response?.data?.message === 'string'
    );
}

Then change your code to use async/await with try/catch instead of old-style Promise .then().catch:

try {
    await yourPromise();

    loginError.value = false;
}
catch( err: unknown ) {

    loginError.value = true;

    if( isMyError( err ) ) {
        console.error( "MyError: %s", err.response.data.message );
    }
    else {
        console.error( "Unexpected error: %o", err );
    }
}

Leave a comment