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
相关产品推荐
相关产品推荐

