Handler.php 4.6KB

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