Throwing aurahandledexception is not sending message correctly to LWC

apexexceptionlightning-web-components

I am calling an apex controller, that has several try-catch blocks that throw exceptions depending on the error or situation, (i am also throwing outside of try catch blocks) this is an example:

try{
                    tipo = [
                        SELECT  id
                        FROM    Tipo_Comprobante_Movimiento_Fondo__c 
                        WHERE   Tipo__c = 'Cobranzas' AND 
                                Empresa__c = :empresaSelected AND
                                Cuenta_Contable__c = :cc
                    ];
                }catch(Exception e){
                    throw new AuraHandledException(System.Label.consulta_saldo_cliente_18);
                }  

Here, I'm sending a label already saved in custom labels, but there are other thrown with normal strings:

throw new AuraHandledException('No se pudo completar el proceso');

For some reason, the message of the error from the LWC side, is "script thrown exception"…

enter image description here

this happened to me today for the first time.. I was already working with these exceptions and this never happened.

Best Answer

I recollect that this is a design quirk of AuraHandledException and that e.g. this is needed (constructor argument probably doesn't matter):

AuraHandledException e = new AuraHandledException(System.Label.consulta_saldo_cliente_18);
e.setMessage(System.Label.consulta_saldo_cliente_18);
throw e;

which is not convenient so best to wrap in a method:

private AuraHandledException newMessageException(String message) {
    AuraHandledException e = new AuraHandledException(message);
    e.setMessage(message);
    return e;
}

so you can then conveniently:

throw newMessageException(System.Label.consulta_saldo_cliente_18);