P
P
Pavel Bezrukov2015-02-26 11:40:41
Yii
Pavel Bezrukov, 2015-02-26 11:40:41

Yii2 how to properly handle an exception?

Good afternoon.
How to properly handle exceptions, such as \SoapFault, so that the application continues to work as if nothing happened?
As I understand it now, error handlers are placed in the yii\base\ErrorHandler::register() method, which leads to undesirable results.
As a crutch, I found such a solution, and it only works for the controller of the heir \yii\web\Controller, for yii\console\Controller the exception could not be prevented at all. In general, I don’t like it at all, I’m missing something quite obvious.

try {
      Yii::$app->errorHandler->unregister();
      $this->_soapClient = new \SoapClient($this->wsdl,
        array(
          'trace' => 1,
          'exceptions' => 1,
          'encoding' => 'UTF-8',
          'passphrase' => ''
        )
      );
    }
    catch(\SoapFault $e) {
      Yii::$app->errorHandler->exception->type = null;
      Yii::$app->errorHandler->register();
    }

As an option, I see how to debug the work of this component in detail, inherit it and come up with my own way out of the situation, but I am sure that such a typical task should be solved somehow much easier and more elegantly. Yes, and you need it in the 1st behavior, and not in the entire application.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vit, 2015-02-26
@fornit1917

What does ErrorHandler have to do with it? ErrorHandler only fires on those exceptions that you yourself did not catch in try..catch.
If you handle an exception, you can ensure that the application continues as if nothing happened.
Here is an example:

try {
  throw new \Exception('Error!');
} catch (\Exception $ex) {
}

//...Можно продолжать работу приложения, как будто не было никаких исключений

I
Igor Vasiliev, 2019-07-09
@Isolution666

Write a function.

...
use yii\base\ViewNotFoundException;
...
try {
    // 1) тут пишите то что хотите проверить
} catch (ViewNotFoundException $e) {
    // 2) тут выводите "удобную" ошибку, чтобы не закрывать ошибкой 500 или той которая вылезает
}

In this case, the path is checked for the existence of the file, if it does not exist, it will return the comment "2)",
that is, if you are annoyed by the ErrorHandler error, write and use it in catch and so on, depending on what prevents the page from working. This solution is suitable for those who have the entire page, and not its fragment, closed with an error. This is how Yii is designed, so that just a little, you will probably see that something is not working for you.
I wish you success.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question