-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: throw BulkInsertQueryException when there are any insert errors
- Loading branch information
Showing
2 changed files
with
66 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
<?php | ||
|
||
namespace DesignMyNight\Elasticsearch\Exceptions; | ||
|
||
use Exception; | ||
|
||
class BulkInsertQueryException extends Exception | ||
{ | ||
private $errorLimit = 10; | ||
|
||
/** | ||
* BulkInsertQueryException constructor. | ||
* | ||
* @param array $queryResult | ||
*/ | ||
public function __construct(array $queryResult) | ||
{ | ||
parent::__construct($this->formatMessage($queryResult), 400); | ||
} | ||
|
||
/** | ||
* Format the error message. | ||
* | ||
* Takes the first {$this->errorLimit} bulk issues and concatenates them to a single string message | ||
* | ||
* @param array $result | ||
* @return string | ||
*/ | ||
private function formatMessage(array $result): string | ||
{ | ||
$message = []; | ||
|
||
$items = array_filter($result['items'] ?? [], function(array $item): bool { | ||
return $item['index'] && !empty($item['index']['error']); | ||
}); | ||
|
||
$items = array_values($items); | ||
|
||
$totalErrors = count($items); | ||
|
||
// reduce to max limit | ||
array_splice($items, 0, $this->errorLimit); | ||
|
||
$message[] = 'Bulk Insert Errors (' . 'Showing ' . count($items) . ' of ' . $totalErrors . '):'; | ||
|
||
foreach ($items as $item) { | ||
$itemError = array_merge([ | ||
'_id' => $item['_id'], | ||
'reason' => $item['error']['reason'], | ||
], $item['error']['caused_by'] ?? []); | ||
|
||
$message[] = implode(': ', $itemError); | ||
} | ||
|
||
return implode(PHP_EOL, $message); | ||
} | ||
} |