I am facing an issue where the code is not entering the catch block in case of an error,
try {
this.doSomething();
} catch (error) {
console.error(error);
}
This problem occurs when "doSomething" returns a promise or runs asynchronous code.
doSomething() {
return new Promise<void>((resolve, reject) => {
this.MySubscription = this.myService.fetchUserDataFromDB().subscribe({
next: (val: any) => {
this.userData = val
resolve()
}, error: (error) => {
let uiErrorMsg = 'Failed to fetch user data';
let consoleErrorMsg = 'Error occurred when calling backend API fetchUserDataFromDB';
if (error instanceof HttpErrorResponse) {
consoleErrorMsg += ` | Status: ${error.status} ${error.statusText} | URL: ${error.url}`;
}
const consoleError = new Error(consoleErrorMsg);
if(error?.status != 401) {
const data = [{ title: 'Alert', message: [uiErrorMsg] }, { okButtonTitle: 'Close' }]
let dialogRef: any = this.dialog.open(ConfirmationModalComponent, {data});
// await firstValueFrom(dialogRef.afterClosed())
}
reject(consoleError);
}
})
})
}
In some instances, I need to call this.doSomething()
without waiting for it to finish, while in other cases I do need to wait. In those situations, I use the keyword await
.
await this.doSomething();
There is a way to handle errors from a promise without awaiting for it, using a different syntax:
this.doSomething().catch(error => {
console.error(error);
});
When I need to wait for it to finish, I use try/catch with "await." However, when I don't require it to finish, I have to use ".catch()" instead of try/catch to catch the errors.
I wonder if there are any plans to enable an async try block so that we can use try/catch syntax in both scenarios, rather than having two different approaches and maintaining consistency with other programming languages that follow standard try/catch behavior?
Perhaps something like
try async {
this.doSomething()
} catch (error) {
console.error(error)
}
and
try {
await this.doSomething()
} catch (error) {
console.error(error)
}
respectively?
Fortunately, my try/catch was primarily for error message handling presentation. However, I can see how this could be frustrating for someone expecting the catch block to execute regardless of whether they used "await" or not when invoking their function.
Is there a way to make a try/catch asynchronous, or should we continue using both .catch() syntax and try/catch syntax?
(I am working with TypeScript 4.9.5, rxjs 7.8.1)