DatabaseQueryException.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\Database\Exceptions; |
| 4 | |
| 5 | use Exception; |
| 6 | |
| 7 | /** |
| 8 | * Class DatabaseQueryException |
| 9 | * |
| 10 | * An exception for when errors occurred within the database while performing a query, which stores the SQL errors the |
| 11 | * database returned |
| 12 | * |
| 13 | * @since 2.9.2 |
| 14 | */ |
| 15 | class DatabaseQueryException extends Exception |
| 16 | { |
| 17 | /** |
| 18 | * @var string[] |
| 19 | */ |
| 20 | private $queryErrors; |
| 21 | |
| 22 | /** |
| 23 | * Creates a new instance wih the query errors |
| 24 | * |
| 25 | * @since 2.9.2 |
| 26 | * |
| 27 | * @param string|string[] $queryErrors |
| 28 | * @param string|null $message |
| 29 | * |
| 30 | * @return DatabaseQueryException |
| 31 | */ |
| 32 | public static function create($queryErrors, $message = null) |
| 33 | { |
| 34 | $error = new self(); |
| 35 | |
| 36 | $error->message = $message ?: 'Query failed in database'; |
| 37 | $error->queryErrors = (array)$queryErrors; |
| 38 | |
| 39 | return $error; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Returns the query errors |
| 44 | * |
| 45 | * @since 2.9.2 |
| 46 | * |
| 47 | * @return string[] |
| 48 | */ |
| 49 | public function getQueryErrors() |
| 50 | { |
| 51 | return $this->queryErrors; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Returns a human readable form of the exception for logging |
| 56 | * |
| 57 | * @since 2.9.2 |
| 58 | * |
| 59 | * @return string |
| 60 | */ |
| 61 | public function getLogOutput() |
| 62 | { |
| 63 | $queryErrors = array_map( |
| 64 | function ($error) { |
| 65 | return " - {$error}"; |
| 66 | }, |
| 67 | $this->queryErrors |
| 68 | ); |
| 69 | |
| 70 | return " |
| 71 | Code: {$this->getCode()}\n |
| 72 | Message: {$this->getMessage()}\n |
| 73 | DB Errors: \n |
| 74 | {$queryErrors} |
| 75 | "; |
| 76 | } |
| 77 | } |
| 78 |