API error handling

User
Assistant
To display an error on the frontend when the API (Probo) returns an error, you need to check for errors in the response JSON (from the proxy endpoint) and handle them appropriately in the JavaScript or inside your Web Component logic (depending on your setup).

Here’s how to **modify your PHP proxy code** to **always return an `error` key if something goes wrong**:

### ✅ Updated `probco_handle_configurator` with error handling:

public function probco_handle_configurator(WP_REST_Request $request) {
    $baseUrl = 'https://api.proboprints.com';
    $token = get_option('probo_api_key');

    $method = $request->get_method();
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Accept: application/json',
        'Content-Type: application/json',
        'Authorization: Basic ' . $token
    ]);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    if ($method === 'POST') {
        $body = $request->get_json_params();

        if (!isset($body['url']) || !isset($body['data'])) {
            return new WP_REST_Response(['error' => 'Invalid request. Missing `url` or `data`.'], 400);
        }

        curl_setopt($curl, CURLOPT_URL, $baseUrl . $body['url']);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body['data']));
    } else {
        $url = $request->get_param('url');

        if (!$url) {
            return new WP_REST_Response(['error' => 'Missing `url` parameter.'], 400);
        }

        curl_setopt($curl, CURLOPT_URL, $baseUrl . $url);
    }

    $response = curl_exec($curl);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($curl);
    curl_close($curl);

    if ($curl_error) {
        return new WP_REST_Response(['error' => 'cURL Error: ' . $curl_error], 500);
    }

    $decoded = json_decode($response, true);

    if ($httpcode >= 400 || isset($decoded['error'])) {
        return new WP_REST_Response([
            'error' => $decoded['error'] ?? 'Unknown error from Probo API',
            'status' => $httpcode,
            'raw' => $decoded
        ], $httpcode);
    }

    return new WP_REST_Response($decoded, $httpcode);
}

### ✅ JavaScript frontend (if you're using `connectConfigurator` directly):

Make sure you catch errors like this:

document.addEventListener('DOMContentLoaded', async () => {
    try {
        await window.connectConfigurator.init({
            proxy: '/wp-json/probo-api/v1/configurator/api',
            language: 'en'
        }).setProduct('YOUR_PRODUCT_CODE_HERE');
    } catch (error) {
        console.error('Error loading configurator:', error);
        alert('Something went wrong while loading the configurator. Please try again.');
    }
});

This ensures:
– PHP returns `error` messages explicitly if the external API or cURL fails.
– Your frontend can detect and show friendly error messages to users.

Let me know if you want to handle/display those errors directly **inside a custom Web Component** too.

User
NO
window.addEventListener("proboConfigurator:finished", function (event) {
console.log("✅ Configuration finished");
jQuery('#launchConfigurator').attr('disabled', false).css('opacity', 1);
// Optionally, you can call updateModal() here if you want to log automatically
const result = window.proboConfigurator.getResult();
const code = window.proboConfigurator.getConfiguration();

console.log("🎯 Final Result:", result);
console.log("📦 Final Configuration:", code);
});
is there any listner for erro

Assistant
Yes, the Probo Configurator emits error-related events that you can listen to using `window.addEventListener`. While they are not always documented thoroughly, the configurator typically emits a custom event on error which you can listen for.

Based on typical implementations and observed behavior, here’s how you can handle **errors**:

### ✅ Listen for configuration errors:

window.addEventListener("proboConfigurator:error", function (event) {
    console.error("❌ Configuration error occurred:", event.detail);

    // You can show a user-friendly error message
    alert("An error occurred while loading the configurator. Please try again later.");

    // Optionally disable a loader or enable the launch button again
    jQuery('#launchConfigurator').attr('disabled', false).css('opacity', 1);
});

### ✅ Bonus: Listen for loading failures

If the configurator fails during the initial load, you might want to capture that too:

window.addEventListener("proboConfigurator:load-failed", function (event) {
    console.error("⚠️ Configurator load failed:", event.detail);

    alert("Failed to load the configurator. Please check your internet connection or try again.");
});

### 📌 Notes:
– `event.detail` often includes an `error` object or `message` from the backend or client-side processing.
– These listeners must be registered **before** the configurator starts.
– You can wrap them all together with your existing `DOMContentLoaded` or `init` logic.

Would you like me to help you display the error inside a custom UI element (like a div or modal) instead of `alert()`?

User
Not working
Assistant
Thanks for checking. Since the `proboConfigurator:error` or `load-failed` events are **not firing** in your setup, it likely means the Probo Configurator Web Component doesn't emit standard custom events for errors — or it's using internal error handling.

Here’s how you can **reliably catch errors from the configurator** by wrapping its `init()` and `setProduct()` in a `try/catch`, and checking for API response errors at that point instead.

### ✅ Reliable error handling pattern:

Replace your configurator setup code with this pattern:

document.addEventListener('DOMContentLoaded', async () => {
    try {
        const configurator = await window.connectConfigurator.init({
            proxy: '/wp-json/probo-api/v1/configurator/api',
            language: 'en' // Or dynamically from PHP
        });

        await configurator.setProduct('<?= esc_attr( $api_code ); ?>');

        // Save reference globally if needed later
        window.proboConfigurator = configurator;

    } catch (error) {
        console.error("❌ Error loading Probo Configurator:", error);

        // Optionally show a user-friendly error
        const errorMessage = (error?.message || error?.error || 'Something went wrong with the configurator.');
        alert(errorMessage);

        jQuery('#launchConfigurator').attr('disabled', false).css('opacity', 1);
    }
});

### 🔍 Why this works:
– The error won’t necessarily come through event listeners like `proboConfigurator:error` if the Web Component isn't dispatching them.
– Wrapping `await connectConfigurator.init()` and `setProduct()` in `try/catch` guarantees you capture errors like:
– API request failed (e.g., invalid token, 500)
– Configurator server unreachable
– Malformed response

### Optional: log full API proxy response
If you're still not seeing helpful error output, log the actual response from your `/wp-json/probo-api/v1/configurator/api` endpoint in the browser console (use Network tab → XHR/Fetch → Response).

If you're still stuck, I can:
– Review your full frontend snippet and identify issues
– Add fallback HTML content (e.g. “Configurator failed to load”)
– Help mock API errors to test behavior

Just let me know.

User
assets/src/probo-product-configurator.js enquee this when probo-configuratore product type o single page woocommerce
Assistant
To enqueue the `assets/src/probo-product-configurator.js` file **only on the single product page for your custom WooCommerce product type `probo-configuratore`**, you can hook into `wp_enqueue_scripts` and conditionally check the product type.

### ✅ Step-by-step code (add to your theme’s `functions.php` or custom plugin):

function enqueue_probo_product_configurator_script() {
    if (is_product()) {
        global $product;

        if ($product && $product->get_type() === 'probo-configuratore') {
            wp_enqueue_script(
                'probo-configurator',
                get_template_directory_uri() . '/assets/src/probo-product-configurator.js', // or get_stylesheet_directory_uri()
                ['jquery'], // dependencies
                '1.0.0',
                true // load in footer
            );
        }
    }
}
add_action('wp_enqueue_scripts', 'enqueue_probo_product_configurator_script');

### ✅ Notes:
– Replace `get_template_directory_uri()` with `get_stylesheet_directory_uri()` if you're using a **child theme**.
– If you’re using a **plugin**, use `plugin_dir_url(__FILE__) . 'assets/src/…'` instead.
– This will enqueue the script **only on single product pages** where the product type is exactly `probo-configuratore`.

Let me know if:
– The JS file is compiled (e.g. via Webpack → should point to `dist/probo-product-configurator.js`)
– You need to enqueue **CSS** too
– You're using a custom product template and want to auto-render the “ tag as well

Leave a Comment

Your email address will not be published. Required fields are marked *