QueryException.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Illuminate\Database;
  3. use Illuminate\Support\Str;
  4. use PDOException;
  5. use Throwable;
  6. class QueryException extends PDOException
  7. {
  8. /**
  9. * The SQL for the query.
  10. *
  11. * @var string
  12. */
  13. protected $sql;
  14. /**
  15. * The bindings for the query.
  16. *
  17. * @var array
  18. */
  19. protected $bindings;
  20. /**
  21. * Create a new query exception instance.
  22. *
  23. * @param string $sql
  24. * @param array $bindings
  25. * @param \Throwable $previous
  26. * @return void
  27. */
  28. public function __construct($sql, array $bindings, Throwable $previous)
  29. {
  30. parent::__construct('', 0, $previous);
  31. $this->sql = $sql;
  32. $this->bindings = $bindings;
  33. $this->code = $previous->getCode();
  34. $this->message = $this->formatMessage($sql, $bindings, $previous);
  35. if ($previous instanceof PDOException) {
  36. $this->errorInfo = $previous->errorInfo;
  37. }
  38. }
  39. /**
  40. * Format the SQL error message.
  41. *
  42. * @param string $sql
  43. * @param array $bindings
  44. * @param \Throwable $previous
  45. * @return string
  46. */
  47. protected function formatMessage($sql, $bindings, Throwable $previous)
  48. {
  49. return $previous->getMessage().' (SQL: '.Str::replaceArray('?', $bindings, $sql).')';
  50. }
  51. /**
  52. * Get the SQL for the query.
  53. *
  54. * @return string
  55. */
  56. public function getSql()
  57. {
  58. return $this->sql;
  59. }
  60. /**
  61. * Get the bindings for the query.
  62. *
  63. * @return array
  64. */
  65. public function getBindings()
  66. {
  67. return $this->bindings;
  68. }
  69. }