Attempting to grasp the concept of error handling in promises has left me confused. Despite researching extensively, I am unable to figure out why it's not working as expected. To simulate a potential error situation, I have created a sample method where I deliberately throw an error:
DeleteProject(id: string, customerId: string): Promise<void> {
throw new Error('test error');
}
Subsequently, I invoke this method in my code like so:
projectService.DeleteProject(state.FocusedProject.ID, state.FocusedProject.CustomerID)
.then(() => {
...actions upon success...
})
.catch(error => {
console.log('caught you');
HandleError(error, 'Delete Project');
});
When the method does not throw an error, everything functions correctly, and the code within the then
block is executed without issues. However, when an error is thrown, an unhandled exception occurs, and the catch
block remains untouched.
My understanding from various resources is that throwing an error inside a function should automatically trigger its catch block and return a rejected promise. So, why isn't it being caught in this scenario?
I suspect I am overlooking something critical, but I cannot pinpoint what it might be. Essentially, I want the catch
block to handle any errors that occur within the invoked method.