

新闻资讯
技术学院laravel 队列在任务失败时调用 `failed()` 方法,但若方法签名强制要求 `exception` 类型参数而实际传入 `null`,将触发“argument 1 passed to ... must be an instance of exception, null given”致命错误。正确做法是显式声明 `\exception $e = null`。
在 Laravel 队列系统中,failed() 方法并非总能接收到异常实例——当任务因超时、进程被强制终止、队列 worker 意外退出或重试耗尽后手动标记为失败等场景下,框架可能传入 null 而非 Exception 对象。此时,若你按 Approach 1 写法 public function failed(Exception $e)(未加全局命名空间前缀且无默认值),PHP 类型声明会严格校验,导致 TypeError。
✅ 正确写法如下(推荐):
public function failed(\Exception $e = null)
{
if ($e) {
\Log::error('Job failed with exception:', [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
} else {
\Log::warning('Job failed without exception (e.g., timeout or manual failure)');
}
// 可在此执行通知、清理、状态更新等逻辑
}⚠️ 关键要点说明:
? 补充建议:
遵循此规范,即可彻底解决该 TypeError,让失败处理逻辑健壮、可维护且符合 Laravel 最佳实践。