【问题标题】:How to catch an exception from another class?如何从另一个类中捕获异常?
【发布时间】:2017-04-07 17:43:37
【问题描述】:

我有一个自定义类:

class ActivationService extends SmsException {

    public function __construct()
    {
          $this->sms = new SmsSender();
    }

    public function method(){
        throw new SmsException(); // My custom exception
    }


    public function send(){
        $this->sms->sendSms($this->phone); // Here's where the error appeared
    }
}

所以,当我调用 $this->sms->sendSms 时,我收到了来自类 sms 的错误。

我正在捕捉自定义异常,例如:

try {    
    $activationService = new ActivationService();
    $activationService->send($request->phone);    
}
catch (SmsException $e) {    
    echo 'Caught exception: ', $e->getMessage(), "\n";
}

但是当我在方法库 (class SmsSender) 中收到错误时:send() 我无法捕获它并收到错误。

我该如何解决?

【问题讨论】:

  • 它可能没有抛出 SmsException。为 \Exception 添加另一个 catch 块,看看它是否捕获了一些东西。
  • 是的,\Exception 有效,但是为什么我的异常不起作用:use Exception; class SmsException extends Exception { // TODO }
  • 你需要\SmsException吗?我知道命名空间可以解决这个问题。

标签: php laravel exception laravel-5.3


【解决方案1】:

这可能是一个命名空间的东西。

如果SmsException 定义在命名空间内,例如:

<?php namespace App\Exceptions;

class SmsException extends \Exception {
    //
}

并且试图捕获异常的代码是在另一个命名空间中定义的,或者根本没有定义,例如:

<?php App\Libs;

class MyLib {

    public function foo() {
        try {

            $activationService = new ActivationService();
            $activationService->send($request->phone);

        } catch (SmsException $e) {

            echo 'Caught exception: ', $e->getMessage(), "\n";
        }
    }
}

那么它实际上会试图捕获App\Libs\SmsException,它没有被定义,所以catch 失败。

如果是这种情况,请尝试将 catch (SmsException $e) 替换为 catch (\App\Exceptions\SmsException $e)(显然使用正确的命名空间),或者在文件顶部添加 use 语句。

<?php App\Libs;

use App\Exceptions\SmsException;

class MyLib {

    // Code here...

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 2015-11-13
    • 2012-11-04
    • 2010-09-16
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多