InsufficientBalanceException.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Module\Transfer\Exceptions;
  3. /**
  4. * 余额不足异常
  5. */
  6. class InsufficientBalanceException extends TransferException
  7. {
  8. private int $userId;
  9. private int $fundId;
  10. private string $requiredAmount;
  11. private string $availableAmount;
  12. public function __construct(
  13. int $userId,
  14. int $fundId,
  15. string $requiredAmount,
  16. string $availableAmount,
  17. string $message = '余额不足'
  18. ) {
  19. $this->userId = $userId;
  20. $this->fundId = $fundId;
  21. $this->requiredAmount = $requiredAmount;
  22. $this->availableAmount = $availableAmount;
  23. $context = [
  24. 'user_id' => $userId,
  25. 'fund_id' => $fundId,
  26. 'required_amount' => $requiredAmount,
  27. 'available_amount' => $availableAmount,
  28. 'shortage' => bcsub($requiredAmount, $availableAmount, 10),
  29. ];
  30. parent::__construct($message, 1001, null, $context);
  31. }
  32. /**
  33. * 获取用户ID
  34. */
  35. public function getUserId(): int
  36. {
  37. return $this->userId;
  38. }
  39. /**
  40. * 获取资金类型ID
  41. */
  42. public function getFundId(): int
  43. {
  44. return $this->fundId;
  45. }
  46. /**
  47. * 获取所需金额
  48. */
  49. public function getRequiredAmount(): string
  50. {
  51. return $this->requiredAmount;
  52. }
  53. /**
  54. * 获取可用金额
  55. */
  56. public function getAvailableAmount(): string
  57. {
  58. return $this->availableAmount;
  59. }
  60. /**
  61. * 获取缺少的金额
  62. */
  63. public function getShortage(): string
  64. {
  65. return bcsub($this->requiredAmount, $this->availableAmount, 10);
  66. }
  67. /**
  68. * 获取详细错误信息
  69. */
  70. public function getDetailedMessage(): string
  71. {
  72. return sprintf(
  73. '用户 %d 的资金类型 %d 余额不足,需要 %s,可用 %s,缺少 %s',
  74. $this->userId,
  75. $this->fundId,
  76. $this->requiredAmount,
  77. $this->availableAmount,
  78. $this->getShortage()
  79. );
  80. }
  81. }