php - Laravel try/catch 不工作

标签 php laravel laravel-5 error-handling try-catch

我搜索了几个问题,原因是我的代码没有正确抛出错误,但我无法弄清楚。

我的 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在找不到模型时抛出异常,这将起作用。
  • 你也可以 catch 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/

    相关文章:

    php - Kohana 3 ORM - 与静态方法的连接和 has_many 关系

    php - 如果在 Laravel 5.5 单元测试中隐藏密码,如何模拟用户创建

    laravel - .homestead 和 Homestead/src/stubs 文件夹中的 homestead.yaml 文件

    php - 下载计数器功能不准确

    Laravel 对created_at 日期字段的强制转换未应用

    laravel-5 - BSoD on vagrant up (KMODE_EXCEPTION_NOT_HANDLED) - Windows 8

    php - 合并两个PNG透明图像

    javascript - 将 grunt 与现有的 wordpress 实例一起使用

    php - 使用 php 和 laravel 对我的 express 员有好处吗?

    php - Laravel 集合 sortBy 没有生效