Handler.php 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. dd($exception);
  54. // Route Not Found 404
  55. if ($exception instanceof RouteNotFoundException) {
  56. return $this->apiExceptionResponse($exception, Response::HTTP_NOT_FOUND, config('response-message.router_failed'));
  57. }
  58. // Not Found 404
  59. if ($exception instanceof NotFoundHttpException) {
  60. $message = $exception->getMessage() ?: config('response-message.not_found');
  61. return $this->apiExceptionResponse($exception, Response::HTTP_NOT_FOUND, $message);
  62. }
  63. // Model Not Found 500
  64. if ($exception instanceof ModelNotFoundException) {
  65. $exception = new NotFoundHttpException($exception->getMessage(), $exception);
  66. }
  67. // Authentication 401
  68. if ($exception instanceof AuthenticationException) {
  69. return $this->apiExceptionResponse($exception, Response::HTTP_UNAUTHORIZED, config('response-message.authenticate_failed'));
  70. }
  71. // Unauthorized
  72. if ($exception instanceof UnauthorizedHttpException) {
  73. return $this->apiExceptionResponse($exception, $exception->getStatusCode(), config('response-message.authorize_failed'));
  74. }
  75. // Http
  76. if ($exception instanceof HttpException) {
  77. return $this->apiExceptionResponse($exception, $exception->getStatusCode(), $exception->getMessage());
  78. }
  79. // Query 500
  80. if ($exception instanceof QueryException) {
  81. $this->apiExceptionResponse($exception, Response::HTTP_INTERNAL_SERVER_ERROR, config('response-message.sql_error'));
  82. }
  83. // Validation 422
  84. if ($exception instanceof ValidationException) {
  85. $validationData = [];
  86. foreach ($exception->errors() as $col => $errorMsg) {
  87. $validationData['errors']['validation'][$col] = $errorMsg[0];
  88. }
  89. return $this->apiExceptionResponse($exception, Response::HTTP_UNPROCESSABLE_ENTITY, config('response-message.validation_failed'), $validationData);
  90. }
  91. // Others: 500 error
  92. return $this->apiExceptionResponse($exception, Response::HTTP_INTERNAL_SERVER_ERROR, 'server error');
  93. }
  94. public function apiExceptionResponse(Throwable $exception, int $code, string $message, array $mergeData = [])
  95. {
  96. if ($code === Response::HTTP_INTERNAL_SERVER_ERROR) {
  97. Log::info($exception->getMessage());
  98. }
  99. $data = [
  100. 'code' => $code,
  101. 'message' => $message,
  102. ];
  103. if (!app()->environment('production')) {
  104. $data['errors'] = [
  105. 'message' => $exception->getMessage(),
  106. 'trace' => $exception->getTrace(),
  107. ];
  108. }
  109. if (!empty($mergeData)) {
  110. $data = array_merge($data, $mergeData);
  111. }
  112. return response()->json($data, $code);
  113. }
  114. }