Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Diferenciación de tipos de excepciones de API (Apex) en JavaScript Try/Catch

En un componente web Lightning , realizo una llamada de API a un método de Apex, que puede generar una excepción. Actualmente, en el bloque catch, hay un código que verifica una cadena específica en la excepción, b/c si es cierto tipo de excepción, queremos mostrar un cierto mensaje al usuario; de lo contrario, queremos mostrar otro mensaje genérico. Obviamente, determinar la excepción específica por cadena no es robusto.

¿Hay una buena manera en JavaScript para determinar qué excepción específica de Apex se lanzó?

Me di cuenta de que el objeto de error que se está pasando actualmente al bloque catch incluye una propiedad de headers , y me pregunto si podría pasar un valor personalizado allí como tipo de exceptionType . Algo como:

 async myFunc() { try { const response = await myApexMethodCall(); } catch(err) { if (err.headers.exceptionType === 'E123') { alert('The order must be associated with a case before processing'); } else { alert('There was an error with the API call. Please contact your administrator'); } } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede crear una clase personalizada que represente la respuesta. Por ejemplo,

 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; } }

Y, luego, en la clase de controlador, puede crear una instancia de CustomOrderStatusResponse en función de diferentes escenarios y puede establecer valores diferentes para errorCode . Por ejemplo,

 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()); } } }

En la interfaz (LWC), puedes hacer algo como esto:

 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); } }

Referencia: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_wire_method y https://developer.salesforce.com/docs/component-library/documentation/en/lwc/ lwc.apex_call_imperative

Espero que esto responda tu pregunta. Cualquier sugerencia y comentario es bienvenido.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!