Skip to content

错误处理 ​

全局异常处理 ​

  • 全局异常处理:bootstrap/app.php
php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;

$app = Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__ . '/../routes/api.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // 注册全局中间件

    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // 这里只是简单处理,可以根据需求自定义
        $exceptions->render(function (Throwable $e) {
            $code = $e->getCode() === 0 ? 999 : $e->getCode();
            $message = $e->getMessage();
            $data = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            // 记录错误日志
            Log::error(json_encode([
                'code' => $code,
                'message' => $message,
                'data' => $data
            ]));
            // 返回错误响应
            return response()->json([
                'code' => $code,
                'message' => $message,
                'data' => env("APP_DEBUG", false) ? $data : null
            ]);
        });
    })->create();

return $app;

自定义异常 ​

  • 创建
bash
php artisan make:exception BusinessException
  • 自定义
php
# 在 `app/Exceptions/BusinessException.php` 中定义自定义异常类
<?php


namespace App\Exceptions;

use RuntimeException;

class BusinessException extends RuntimeException
{
    public function __construct(string $message = '', int $code = 600)
    {
        parent::__construct($message, $code);
    }
}
  • 使用
php
throw new BusinessException('自定义异常信息',10001);