You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9脚本报错返回异常而非配置JSON的解决方法

修复Laravel 9脚本失败时未返回自定义JSON响应的问题

1. 修正异常处理器逻辑

Laravel 9及后续版本的异常处理核心在app/Exceptions/Handler.php的register方法中,若之前调整后无效,大概率是未正确区分API请求与网页请求,导致异常处理器尝试渲染不存在的视图。修改该文件如下:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Http\Request;

class Handler extends ExceptionHandler
{
    protected $dontReport = [
        // 无需上报的异常类可在此添加
    ];

    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register()
    {
        $this->reportable(function (Throwable $e) {
            // 异常上报逻辑(如写入日志)
        });

        // 自定义异常响应规则
        $this->renderable(function (Throwable $e, Request $request) {
            // 识别API请求:匹配api前缀路由或期望JSON响应的请求
            if ($request->is('api/*') || $request->wantsJson()) {
                return response()->json([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                    // 仅调试模式返回栈信息
                    'trace' => config('app.debug') ? $e->getTrace() : []
                ], $this->getExceptionStatusCode($e));
            }

            // 非API请求按默认逻辑处理
            return $this->defaultRender($request, $e);
        });
    }

    // 辅助方法:获取异常对应的HTTP状态码
    private function getExceptionStatusCode(Throwable $e): int
    {
        return method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;
    }
}

2. 解决View [welcome] not found异常

该报错的核心是异常处理器在处理非API请求时,尝试渲染默认错误视图但视图文件不存在:

  • 若项目不需要网页端错误视图,确保所有API请求被步骤1的逻辑覆盖,避免触发视图渲染流程;
  • 若需要网页端错误页面,在resources/views/errors/目录下创建对应状态码的视图文件(如500.blade.php、404.blade.php),Laravel会自动匹配渲染。

3. 针对业务代码的定制化异常处理(可选)

如果想对用户创建这类特定业务逻辑返回更精准的响应,可手动捕获异常:

try {
    $user = new User();
    $user->name = $validatedData['name'];
    $user->email = $validatedData['email'];
    $user->password = Hash::make($validatedData['password']);
    $user->token = $token;
    $user->save();

    return response()->json(['status' => 'success', 'message' => '用户创建成功']);
} catch (\Throwable $e) {
    return response()->json([
        'status' => 'error',
        'message' => '用户创建失败:'.$e->getMessage()
    ], 500);
}

4. 验证基础配置

  • 检查config/app.php的debug项:生产环境设为false避免暴露敏感信息,开发环境可设为true方便调试;
  • 确保API路由都定义在routes/api.php中,这类路由默认带有api/前缀,便于异常处理器识别。

内容的提问来源于stack exchange,提问作者faba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:13:22