Promises can simplify code that handles the success or failure of asynchronous calls. To use error handling with promises, use the catch() method on the promise that is returned from calling an API method.
The catch() method returns a promise and accepts a single function parameter that’s called if the promise is rejected. This function has one argument that shows the reason for the rejection. The promise returned by catch() is rejected if the function that is passed in either throws an error or returns a promise that’s rejected. Otherwise, the promise is resolved.
Best Practices for Error Handling
When handling errors for Lightning console apps, consider validating the input, logging the error message, and provide user feedback if the method fails. For example, if you use setSelectedNavigationItem(), check that the developer name is valid and handle any errors accordingly.
This error is thrown when the navigation item isn’t found.
1try{2 await setSelectedNavigationItem('NonExistentItem');3}catch(error){4 console.error('Navigation item not found:', error);5}
Error: "The selected navigation item has unsaved changes. Save the changes, then try again.
This error is thrown when you have unsaved changes.
1try{2 await refreshNavigationItem();3}catch(error){4 if(error.message.includes('unsaved changes')){5 console.log('Please save changes before refreshing');6}7}