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

Laravel控制器中Attempt to assign property on null异常未捕获求助

问题分析与解决

核心原因

$resp->b->a = 1触发的"Attempt to assign property on null"属于PHP的Error类实例,而非Exception类实例。你的catch块仅捕获Exception类型,因此无法拦截该错误,最终导致Laravel返回500内部服务器错误。而手动throw new Exception()属于Exception类型,自然能被正常捕获。

解决方案

方案1:捕获所有可抛出类型(推荐)

将catch的目标改为\Throwable,它是PHP中所有可抛出对象(包括Error和Exception)的父类:

function update(Request $req)
{
    try {
        $resp = new stdClass();
        $resp->b->a = 1;
    } catch (\Throwable $ex) {
        return response('An error has occured.' . $ex->getMessage(), 400);
    }
}

方案2:同时捕获Error和Exception

如果需要区分处理系统错误与业务异常,可以分别捕获:

function update(Request $req)
{
    try {
        $resp = new stdClass();
        $resp->b->a = 1;
    } catch (\Error $ex) {
        return response('A system error has occured.' . $ex->getMessage(), 400);
    } catch (\Exception $ex) {
        return response('An application error has occured.' . $ex->getMessage(), 400);
    }
}

方案3:从根源避免错误

提前初始化$resp->b为stdClass对象,彻底杜绝该错误的发生:

function update(Request $req)
{
    try {
        $resp = new stdClass();
        $resp->b = new stdClass(); // 先初始化b属性
        $resp->b->a = 1;
    } catch (\Exception $ex) {
        return response('An error has occured.' . $ex->getMessage(), 400);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:47:17