I am having problems getting the below code to go into the catch block on error,
try {
this.doSomething();
} catch (error) {
console.error(error);
}
if “doSomething” returns a promise / 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);
}
})
})
}
Some places I need to call this.doSomething()
not caring exactly when it finishes, other places I do care, and in those cases put the word await
in front when I want the code to wait until it finishes before it proceeds to the next line.
await this.doSomething();
There is apparently a way to catch the errors of a promise without awaiting for it, but it’s in a different syntax:
this.doSomething().catch(error => {
console.error(error);
});
So where I need to wait for it to finish I use try/catch with “await” as one would expect, but when I don’t care when it finishes I am needing to call it with “.catch()” instead of try/catch to catch the errors.
Is there any plan to allow marking a try block as async, so that we can keep try/catch syntax in both scenarios, so we don’t need two different syntaxes and can be more consistent with other programming languages where try/catches reliably go in the catch blocks when they are expected to?
Such as something like
try async {
this.doSomething()
} catch (error) {
console.error(error)
}
and
try {
await this.doSomething()
} catch (error) {
console.error(error)
}
respectively?
Luckily the purpose of my try catch was simply to handle printing of error messages in a visually pleasing manner. But I can imagine this causing a lot of frustration for someone who was relying on their catch block being entered regardless of whether they called their function with “await” or not.
Is there a way to make a try/catch asynchronous or do we need to maintain both .catch() syntax and try/catch syntax?
(I am using typescript 4.9.5, rxjs 7.8.1)