You can use an AuraHandledException in your apex class. See the below example.
// Best practice: user-friendly error message provided by an AuraHandledException
@AuraEnabled
public static void triggerBasicAuraHandledError() {
try {
integer a = 1 / 0; // Division by zero causes exception
}
catch (Exception e) {
// "Convert" the exception into an AuraHandledException
throw new AuraHandledException('Darn it! Something went wrong: '
+ e.getMessage());
}
finally {
// Something executed whether there was an error or not
}
}
This is how you can handle the AuraHandledException in the component.
function(response) {
// Checking the server response state
let state = response.getState();
if (state === "SUCCESS") {
// Process server success response
let returnValue = response.getReturnValue();
}
else if (state === "ERROR") {
// Process error returned by server
let errors = response.getError();
let message = 'Unknown error'; // Default error message
// Retrieve the error message sent by the server
if (errors && Array.isArray(errors) && errors.length > 0) {
message = errors[0].message;
}
// Display the message
console.error(message);
}
else {
// Handle other reponse states
}
}
Refer the detailed information here.