Handler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Exceptions;
  3. use Catch\Enums\Code;
  4. use Catch\Exceptions\CatchException;
  5. use Catch\Exceptions\FailedException;
  6. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  7. use Illuminate\Http\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Throwable;
  10. class Handler extends ExceptionHandler
  11. {
  12. /**
  13. * A list of exception types with their corresponding custom log levels.
  14. *
  15. * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
  16. */
  17. protected $levels = [
  18. //
  19. ];
  20. /**
  21. * A list of the exception types that are not reported.
  22. *
  23. * @var array<int, class-string<\Throwable>>
  24. */
  25. protected $dontReport = [
  26. //
  27. ];
  28. /**
  29. * A list of the inputs that are never flashed to the session on validation exceptions.
  30. *
  31. * @var array<int, string>
  32. */
  33. protected $dontFlash = [
  34. 'current_password',
  35. 'password',
  36. 'password_confirmation',
  37. ];
  38. /**
  39. * Register the exception handling callbacks for the application.
  40. *
  41. * @return void
  42. */
  43. public function register()
  44. {
  45. $this->reportable(function (Throwable $e) {
  46. //
  47. });
  48. }
  49. /**
  50. * render
  51. *
  52. * @param $request
  53. * @param Throwable $e
  54. * @return JsonResponse|Response
  55. * @throws Throwable
  56. */
  57. public function render($request, Throwable $e): JsonResponse|Response
  58. {
  59. $message = $e->getMessage();
  60. if (method_exists($e, 'getStatusCode')) {
  61. if ($e->getStatusCode() == Response::HTTP_NOT_FOUND) {
  62. $message = '路由未找到或未注册';
  63. }
  64. }
  65. $e = new FailedException($message ?: 'Server Error', $e instanceof CatchException ? $e->getCode() : Code::FAILED);
  66. $response = parent::render($request, $e);
  67. $response->header('Access-Control-Allow-Origin', '*');
  68. $response->header('Access-Control-Allow-Methods', '*');
  69. $response->header('Access-Control-Allow-Headers', '*');
  70. return $response;
  71. }
  72. }