我只有api laravel项目.如果我通过设置APP_DEBUG=false来关闭.env文件中的调试模式,我的应用程序就会抛出Server error来处理不应该向用户显示的错误.

但是它返回如下json响应:

{
    "message": "Server Error"
}

我想把密码 keys 加到屁股上.我想要实现的目标是:

{
    "code": 500,
    "message": "Server Error"
}

我到目前为止所try 的(Handlerregister种方法):

    $this->renderable(function (Throwable|Exception $e) {
        return response()->json([
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        ], $e->getCode());
    });

但这将返回不应该显示给用户的异常消息.我需要这样的史密斯:

    $this->renderable(function (Throwable|Exception $e) {
        // ReportableException doesn't exist in laravel
        if($e instanceof ReportableException){
            return response()->json([
                'code' => 500,
                'message' => 'Server error'
            ], 500);
        }

        return response()->json([
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        ], $e->getCode());
    });

推荐答案

我发现有isHttpException种方法可以用来判断异常是可以报告给用户的还是不可以报告的.这就是我的解决方案:

   $this->renderable(function (Throwable $e) {
        if (!$this->isHttpException($e)){
            return response()->json([
                'code' => 500,
                'message' => "Internal server error"
            ], 500);
        }
        $code = $e->getCode() == 0 ? 500 : $e->getCode();

        return response()->json([
            'code' => $code,
            'message' => $e->getMessage()
        ], $code);
    });

Php相关问答推荐

在AJAX请求后,Laravel重定向.(不允许使用方法)

如果日期是过go 日期,则隐藏事件发布类型

使用随机生成器在MYSQL中创建唯一ID-定义一个数组来存储已知ID是否安全

为什么PHP PDO忽略NOT NULL约束?

扩展 WooCommerce 类触发未捕获错误:未找到WC_Coupon类

在 PHP 中将字符串分解为数组(字符串类似于 WP 短代码)

根据页面以及是否在促销,向 WooCommerce 中显示的价格添加前缀

从 XAMPP 运行 shell 脚本时,意外标记(附近出现语法错误

我不明白为什么我收到未定义的数组键异常错误 - Laravel 9 PHP 8

PHP 解析 XML 以获取多个深度的所有字符串值

Google Drive API:为什么使用服务帐户在下载文件时会将我带到 Google Drive 登录窗口?

无法在 Laravel 中实例化抽象类 ProductAbstract

将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

根据所选付款方式启用/禁用 WooCommerce 所需的 checkout 字段

在 WooCommerce wc_get_products 函数中处理自定义分类法

图像未在 Laravel Ajax Crud 中显示

Woocommerce单个添加到购物车页面中的产品动态定价

PHP使用三元运算符进行null合并(再次)

将 HTML 表单链接到 SQLite 数据库

服务器发送的事件:EventSource 抛出 MIME 错误