I am interested in how to handle errors/exceptions/returned data correctly.
For example, I have a script which creates, updates and deletes products data.
Here is method that receives data from an API, processes and decides what to create/update/delete.
private function importProducts($brand)
{
$products = $this->dsApi->getProductsByBrand($brand);
//returns ['create' => [], 'update' => [], 'delete' => [] ]
$preparedProducts = $this->prepareProducts($products, $brand);
foreach ($preparedProducts['delete'] as $key => $product) {
$this->deleteProduct($product);
$this->log->info(
'Brand ' . $brand->name . '(' . $brand->id_brand . ')'
. ' id: ' . $product . ' was deleted'
);
}
foreach ($preparedProducts['create'] as $key => $product) {
$this->importProduct($product, $brand);
$this->log->info(
'Brand ' . $brand->name . '(' . $brand->id_brand . ') sku: ' . $product['sku'] . ' was imported'
);
}
foreach ($preparedProducts['update'] as $key => $product) {
$this->importProduct($product, $brand, $product['idProductWc']);
$this->log->info(
'Brand ' . $brand->name . '(' . $brand->id_brand . ') sku: ' . $product['sku']
. ' id: ' . $product['idProductWc'] . ' was updated'
);
}
}
And for example deleteProduct()
method:
private function deleteProduct($product)
{
wp_delete_post($product, true);
$args = [
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => (int) $product['idProductWc'],
'post_status' => 'inherit',
'post_type' => 'attachment',
];
$child = get_children($args);
foreach ($child as $id => $item) {
wp_delete_attachment($id, true);
}
}
Is the deletion method written correctly? Is it necessary to handle an error in wp_delete_post()
method? How to handle it? What to write in logs in this case? Should the method return a response?