Handler.php 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. <?php
  2. namespace App\Exceptions;
  3. use Throwable;
  4. use Illuminate\Http\Response;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Database\QueryException;
  7. use Illuminate\Auth\AuthenticationException;
  8. use Illuminate\Validation\ValidationException;
  9. use Illuminate\Database\Eloquent\ModelNotFoundException;
  10. use Symfony\Component\HttpKernel\Exception\HttpException;
  11. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  12. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  15. class Handler extends ExceptionHandler
  16. {
  17. /**
  18. * A list of the exception types that are not reported.
  19. *
  20. * @var array<int, class-string<Throwable>>
  21. */
  22. protected $dontReport = [
  23. //
  24. ];
  25. /**
  26. * A list of the inputs that are never flashed for validation exceptions.
  27. *
  28. * @var array<int, string>
  29. */
  30. protected $dontFlash = [
  31. 'current_password',
  32. 'password',
  33. 'password_confirmation',
  34. ];
  35. /**
  36. * Register the exception handling callbacks for the application.
  37. *
  38. * @return void
  39. */
  40. public function register()
  41. {
  42. $this->reportable(function (Throwable $e) {
  43. //
  44. });
  45. $this->renderable(function (Throwable $e, $request) {
  46. if ($request->is('api/*')) {
  47. return $this->handleApiException($e);
  48. }
  49. });
  50. }
  51. public function handleApiException(Throwable $exception)
  52. {
  53. // Route Not Found 404
  54. if ($exception instanceof RouteNotFoundException) {
  55. return $this->apiExceptionResponse($exception, Response::HTTP_NOT_FOUND, config('response-message.router_failed'));
  56. }
  57. // Not Found 404
  58. if ($exception instanceof NotFoundHttpException) {
  59. $message = $exception->getMessage() ?: config('response-message.not_found');
  60. return $this->apiExceptionResponse($exception, Response::HTTP_NOT_FOUND, $message);
  61. }
  62. // Model Not Found 500
  63. if ($exception instanceof ModelNotFoundException) {
  64. $exception = new NotFoundHttpException($exception->getMessage(), $exception);
  65. }
  66. // Authentication 401
  67. if ($exception instanceof AuthenticationException) {
  68. return $this->apiExceptionResponse($exception, Response::HTTP_UNAUTHORIZED, config('response-message.authenticate_failed'));
  69. }
  70. // Unauthorized
  71. if ($exception instanceof UnauthorizedHttpException) {
  72. return $this->apiExceptionResponse($exception, $exception->getStatusCode(), config('response-message.authorize_failed'));
  73. }
  74. // Http
  75. if ($exception instanceof HttpException) {
  76. return $this->apiExceptionResponse($exception, $exception->getStatusCode(), $exception->getMessage());
  77. }
  78. // Query 500
  79. if ($exception instanceof QueryException) {
  80. $this->apiExceptionResponse($exception, Response::HTTP_INTERNAL_SERVER_ERROR, config('response-message.sql_error'));
  81. }
  82. // Validation 422
  83. if ($exception instanceof ValidationException) {
  84. $validationData = [];
  85. foreach ($exception->errors() as $col => $errorMsg) {
  86. $validationData['errors']['validation'][$col] = $errorMsg[0];
  87. }
  88. return $this->apiExceptionResponse($exception, Response::HTTP_UNPROCESSABLE_ENTITY, config('response-message.validation_failed123'), $validationData);
  89. }
  90. // Others: 500 error
  91. return $this->apiExceptionResponse($exception, Response::HTTP_INTERNAL_SERVER_ERROR, 'server error');
  92. }
  93. public function apiExceptionResponse(Throwable $exception, int $code, string $message, array $mergeData = [])
  94. {
  95. if ($code === Response::HTTP_INTERNAL_SERVER_ERROR) {
  96. Log::info($exception->getMessage());
  97. }
  98. $data = [
  99. 'code' => $code,
  100. 'message' => $message,
  101. ];
  102. if (!app()->environment('PRO')&&!app()->environment('pro')) {
  103. $data['errors'] = [
  104. 'message' => $exception->getMessage(),
  105. 'trace' => $exception->getTrace(),
  106. ];
  107. }
  108. if (!empty($mergeData)) {
  109. $data = array_merge($data, $mergeData);
  110. }
  111. return response()->json($data, $code);
  112. }
  113. }