我搜索了几个问题,原因是我的代码没有正确抛出错误,但我无法弄清楚。
我的 Controller 中有以下功能
<?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
最佳答案
有两种方法可以解决这个问题。首先要注意的是ERROR: Call to a member function delete() on null
也不异常(exception),这是一个 fatal error 。
findOrFail
而不是 find
在找不到模型时抛出异常,这将起作用。 Throwable
而不是 Exception
捕获错误和异常(自 PHP7 起)或只是 Error
捕捉错误。 As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.
在此处阅读有关 PHP7 错误处理的更多信息:http://php.net/manual/en/language.errors.php7.php
关于php - Laravel try/catch 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844099/