ResponseException.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Http\Response;
  5. /**
  6. * 用作逻辑错误返回.
  7. * Class ResponseException
  8. * @package App\Exceptions
  9. * Auth Zhong
  10. * Date 2018/10/31
  11. */
  12. class ResponseException extends Exception
  13. {
  14. /**
  15. * @var Response
  16. */
  17. protected $response;
  18. public function __construct($response, $data = [], $code = 400)
  19. {
  20. if ($response instanceof Response) {
  21. $this->response=$response;
  22. } else {
  23. $responseData['message']=$response;
  24. $responseData['errors']=$data;
  25. if (request()->isXmlHttpRequest()) {
  26. $this->response=response()->json($responseData)->setStatusCode($code);
  27. } else {
  28. $this->response=response()->view('errors.'.$code, $responseData, $code);
  29. }
  30. }
  31. }
  32. /**
  33. * Render the exception into an HTTP response.
  34. *
  35. * @return \Illuminate\Http\Response
  36. */
  37. public function render()
  38. {
  39. return $this->response;
  40. }
  41. /**
  42. * @return Response
  43. */
  44. public function getResponse(): Response
  45. {
  46. return $this->response;
  47. }
  48. }