Home > Net >  How do I check the type of an exception that I don't have available?
How do I check the type of an exception that I don't have available?

Time:01-04

I have an exception thrown from a package imported by another package, I do not have access to that exception's constructor but I do know that this exception might have a statusCode field on it. How do I access this field safely when using typescript 4.4's useUnknownInCatchVariables?

CodePudding user response:

You could define your own class which would extend the Error class, and add a statusCode field to it. Then in the catch block you could check if the caught error is an instance of your error:

class PackageException extends Error {
    statusCode: number = 0;
}

try {
    // something
} catch (err) {
    if (err instanceof PackageException) {
        if (err.statusCode === 404) {
            // handle not found error
        } else if (err.statusCode === 403) {
            // handle forbidden error
        }
    }
}

TS playground link

CodePudding user response:

Inside catch err can be of any type

try {
    // something
} catch (err: any) {
        if (err.statusCode === 404) {
            // handle not found error
        } else if (err.statusCode === 403) {
            // handle forbidden error
        }
}
  •  Tags:  
  • Related