I have the below code to throw an exception from Apex
@AuraEnabled()
public static void associateAccount(string userId, string accountSAPNumber) {
if(String.isBlank(userId) || string.isBlank(accountSAPNumber)) {
throw new AuraHandledException('Please specify both User Email2 and SAP Number2');
}
List<user> users = [SELECT Id, Name,Email FROM User WHERE Email =: userId AND IsActive = true AND Profile.Name ='OEA Customer'];
if(users == null || users.size() <= 0) {
NoDataFoundException noUsersFound = new NoDataFoundException();
noUsersFound.setMessage('No users found with the specified email address: ' + userId);
throw noUsersFound;
}
Id accountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('OEA Customer Location').getRecordTypeId();
accountSAPNumber = '%' + accountSAPNumber;
List<Account> accounts = [SELECT Id FROM Account WHERE RecordTypeId =:accountRecordTypeId AND SAP_Number__c like :accountSAPNumber];
if(accounts == null || accounts.size() <= 0) {
NoDataFoundException noAccountFound = new NoDataFoundException();
noAccountFound.setMessage('No accounts found with the specified SAP Number: ' + accountSAPNumber);
throw noAccountFound;
}
else if(accounts.size() > 1) {
SearchException moreThan1Account = new SearchException();
moreThan1Account.setMessage('More than 1 account found with the specified SAP Number: ' + accountSAPNumber);
throw moreThan1Account;
}
OEA_NewContactFormController.accountMethod(userId, accountSAPNumber);
}
I am not able to catch this exception in my LWC Controller using the below
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then((result) => {
try {
console.log("return from remote call " + result);
this.modalPopUpToggleFlag = false;
} catch (error) {
console.log('some error');
}
})
.error((error) => {
console.log("some error in code");
/*if (Array.isArray(error.body)) {
console.log(
"error message :" + error.body.map((e) => e.message).join(", ")
);
} else if (typeof error.body.message === "string") {*/
//console.log("error message :" + error);
//}
})
.finally(() => {
console.log("finally message :");
});
}
This always gives me an error on the console as "Uncaught (in promise)" and with the details of the exception. How can I catch this exception in a handled way.
The correct syntax is .then().catch().finally()
, while you wrote .then().error().finally()
.
Moreover associateAccount returns void
, so there will be no result
received from then
. There is also no reason to wrap this.modalPopUpToggleFlag = false;
in a try-catch, only if your never defined modalPopUpToggleFlag
there could be an error.
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then(() => {
console.log("return from remote call);
this.modalPopUpToggleFlag = false;
})
.catch((error) => {
console.log("some error in code:", error);
});
}
Here is a good reading about Using Promises in Javascript