I can't catch an error from a Rest ful when sending a mail

Viewed 26

I have a method that consumes a WS to send a mail. If the email account is real it works fine, but if the email account is not real it returns a 500 error through the getResponseCode. The bad thing is that additional it shows me a window with the indicated error.

Before running it make sure to run the following method:

ConnectionRequest.setHandleErrorCodesInGlobalErrorHandler(false);

My Method:

public static Response imprimePedido(Long pedidoId) {
    String serverPost = "";
    Response<String> r = null;
    if (Preferences.get("correo_prueba", null) != null) {
        serverPost = SERVER_URL + "blank_factura_impresion_pdf/blank_factura_impresion_pdf.php?pedidoId=" + Long.toString(pedidoId) + "&correo_prueba=" + Preferences.get("correo_prueba", null);
    } else {
        serverPost = SERVER_URL + "blank_factura_impresion_pdf/blank_factura_impresion_pdf.php?pedidoId=" + Long.toString(pedidoId);
    }
    try {
        r = Rest.post(serverPost).
                header("token", UsuarioService.getToken()).
                jsonContent().getAsString();
        if (r.getResponseCode() != 200) {
            System.out.println("No pude enviar correo");
            log("Error: " + r.getResponseErrorMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return r;
}

Window Error: enter image description here

1 Answers

ConnectionRequest.setHandleErrorCodesInGlobalErrorHandler(false); makes sense only for old apps that relies on a misbehavior of old versions of Codename One. So, I suggest you remove it.. The purpose of this method is documented here: https://www.codenameone.com/blog/terse-table-radar-chart-networking.html#_networking_enhancements

I suppose that the cause of your issue is the default network error listener, which is usually in the init(). Its code is something like this:

        addNetworkErrorListener(err -> {
            // prevent the event from propagating
            err.consume();
            if(err.getError() != null) {
                Log.e(err.getError());
            }
            Log.sendLogAsync();
            Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
        });

I suggest you customize that code with better error management, like the one I told in this answer: https://stackoverflow.com/a/68773491

However, that's not all. I have had a similar problem to yours with sending emails. A 500 error doesn't let the user know that they misspelled the email address. So I modified the server-side code to return a 200 code, but with a different response message, e.g., "correctlySent" or "invalidEmailAddress". This way, the app can correctly inform the user and distinguish between this type of error and other errors.

Related