Reputation: 1
I'm trying to fix a problem with my code. I have a function that is throwing an error, and I'm trying to handle it but for some reason my try/catch block won't catch the error. I think it's throwing two errors, because it does enter the catch block, but the console still shows an error message. Is there any way I might fix this? Thanks
try{
await renameItem(myID, newName); //The error is triggered by this line
} catch(error) {
console.log("There was an error");
await renameItem(myID, oldName);
return;
}
ETA the renameItem function posts some data to another function which validates the data and puts it into a database. If the data is invalid it throws an exception.
Upvotes: 0
Views: 188
Reputation: 21
Without seeing your renameItem definition, it is difficult to diagnose the problem. However, the reason the error is displaying in the console is because your try/catch will not handle an error in the catch block. You would have to wrap the call to renameItem in try/catch within the catch block, which is NOT ideal. I would recommend moving your try/catch logic within the renameItem function and handling errors at that scope if additional actions are required on failure. Also, if the point of this method is to simply rename an item, and renaming fails, you should not have to reset the old name. This is especially true if persisting to a database. If the database update fails, nothing has changed.
Upvotes: 1