I have created a custom error and set a custom message for it. then somewhere I throw my custom error and catch somewhere else. I want to access to message that I set before .but TypeScript tell me that error has unknown type! how can I fix it?
async activeAccount(uuid: string) {
try {
const response = await ApiClient(
METHODS.GET,
"Account/approveEmail",
false,
{
uuid
}
);
} catch (error) {
this.showToastError(error.message);
}
}
There is no guarantee that the thing caught by catch is actually an error because throw can throw anything (that's why the type is unknown, you have to narrow it with checks to do anything with it). The compiler is warning you appropriately that you are failing to consider something like this:
try {
throw undefined;
} catch (err) {
console.log(err.message); // oops
}
to fix this, you can add a check to make sure that you have an actual error:
try {
...
} catch (err) {
if (err instanceof Error) {
console.log(err.message); // ok
}
}