【发布时间】:2019-01-21 11:15:13
【问题描述】:
我搜索了几个问题,原因是我的代码没有正确抛出错误,但我无法弄清楚。
我的控制器中有以下功能
<?php
public function suspend($id)
{
try {
$this->collection = $this->class::find($id);
$this->collection->delete();
return $this->respond_with_success();
} catch (\Exception $e) {
return $this->respond_with_error('Failed to suspend resource with id: ' . $id);
}
}
作为参考,我正在使用软删除。一旦没有问题,我就可以暂停资源。如果我尝试挂起一个已经挂起的程序,Laravel 会正确抛出 500,正如我在日志文件 /storage/logs/laravel.log 中看到的那样@
这是我看到的错误的一部分;
local.ERROR: Call to a member function delete() on null....
不使用
withTrashed() 在查询中,很明显找不到一行。所以这是有道理的。
太好了……那为什么我的catch 没有真正捕捉到任何东西?我在浏览器中看到 500 错误,但我的应用程序应该允许我继续并正确处理该错误。但它只是完全倒塌......
respond_with_error 函数如下。我尝试在测试中将 $code 更改为 200,但这并没有改变任何东西。我已经测试过返回一个简单的字符串而不是使用这个函数,但没有成功,所以我认为这部分没有任何问题。
<?php
protected function respond_with_error($message = 'error', $code = 500)
{
return Response::json([
'success' => false,
'message' => $message,
], $code);
}
我正在运行 Laravel 5.6.29
【问题讨论】:
标签: php laravel laravel-5 error-handling try-catch