您可以创建一个代表响应的自定义类。例如,
public with sharing class CustomOrderStatusResponse {
@AuraEnabled
public String errorCode { get; set; }
@AuraEnabled
public Map<String, String> result { get; set; }
public CustomOrderStatusResponse(String errorCode, Map<String, String> result) {
this.errorCode = errorCode;
this.result = result;
}
}
然后,在控制器类中,您可以根据不同的场景创建CustomOrderStatusResponse 的实例,并可以为errorCode 设置不同的值。例如,
public with sharing class CustomOrderStatus {
@AuraEnabled
public static CustomOrderStatusResponse getOrderStatus(String orderId){
CustomOrderStatusResponse response;
try {
if (orderId.equals('123')) {
Map<String, String> result = new Map<String, String>();
result.put('status', 'completed');
response = new CustomOrderStatusResponse(null, result);
} else if (orderId.equals('456')) {
response = new CustomOrderStatusResponse('E123', null);
} else if (orderId.equals('789')) {
response = new CustomOrderStatusResponse('E789', null);
}
return response;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
在前端 (LWC) 中,您可以执行以下操作:
import { LightningElement } from 'lwc';
import getOrderStatus from "@salesforce/apex/CustomOrderStatus.getOrderStatus";
export default class OrderStatus extends LightningElement {
handleFirstClick(event) {
this.displayOrderStatus('123');
}
handleSecondClick(event) {
this.displayOrderStatus('456');
}
handleThirdClick(event) {
this.displayOrderStatus('789');
}
displayOrderStatus(orderId) {
getOrderStatus({ orderId: orderId })
.then(response => {
if (response.errorCode === 'E123') {
alert('The order must be associated with a case before processing');
} else if (response.errorCode) {
alert('There was an error with API Call');
} else {
alert('Status: ' + response.result.status);
}
})
.catch(console.error);
}
}
参考:https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_wire_method 和 https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_call_imperative
我希望这能回答您的问题。欢迎任何建议和cmets。