1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Exceptions;
- use Closure;
- use Exception;
- use Illuminate\Auth\AuthenticationException;
- use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- use Illuminate\Session\TokenMismatchException;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Validation\ValidationException;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- use Throwable;
- class Handler extends ExceptionHandler
- {
- /**
- * The list of the inputs that are never flashed to the session on validation exceptions.
- *
- * @var array<int, string>
- */
- protected $dontFlash = [
- 'current_password',
- 'password',
- 'password_confirmation',
- ];
- /**
- * Register the exception handling callbacks for the application.
- */
- public function register(): void
- {
- $this->reportable(function (Throwable $e) {
- $context = [
- 'exception' => get_class($e),
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'trace' => $e->getTraceAsString(),
- 'url' => request()->fullUrl(),
- 'method' => request()->method(),
- 'ip' => request()->ip(),
- 'user_agent' => request()->userAgent(),
- ];
-
- if ($e instanceof NotFoundHttpException) {
- Log::error('Route not found: ' . request()->fullUrl(), $context);
- } else {
- Log::error($e->getMessage(), $context);
- }
- });
- $this->renderable(function (NotFoundHttpException $e) {
- return response()->json([
- 'code' => 404,
- 'msg' => 'Route not found: ' . request()->fullUrl()
- ], Response::HTTP_NOT_FOUND);
- });
- $this->renderable(function (TokenMismatchException $e) {
- return response()->json([
- 'code' => $e->getCode() ?: 419,
- 'msg' => $e->getMessage()
- ], 419);
- });
- $this->renderable(function (AuthenticationException $e) {
- return response()->json([
- 'code' => $e->getCode() ?: 401,
- 'msg' => '登录超时!'
- ], Response::HTTP_UNAUTHORIZED);
- });
- $this->renderable(function (ValidationException $e) {
- return response()->json([
- 'code' => $e->getCode() ?: 422,
- 'msg' => $e->getMessage()
- ], Response::HTTP_UNPROCESSABLE_ENTITY);
- });
- $this->renderable(function (ApiException $e) {
- return response()->json([
- 'code' => $e->getCode() ?: 200,
- 'msg' => $e->getMessage()
- ], 200);
- });
- $this->renderable(function (Throwable $e) {
- return response()->json([
- 'code' => $e->getCode() ?: 500,
- 'msg' => $e->getMessage()
- ], Response::HTTP_INTERNAL_SERVER_ERROR);
- });
- }
- }
|