【问题标题】:Use try/catch doesn't catch the exception使用 try/catch 不会捕获异常
【发布时间】:2019-11-28 12:53:07
【问题描述】:

我有以下代码:

<?php
require 'vendor/autoload.php';
use Transmission\Exception;

try{
    $transmission = new Transmission\Client($hostname, $port, $username, $password, $httpClientBuilder = null);
} catch (NetworkException $e) {
    $result = array("Error" => "Remote access is disabled");
}

我正在尝试捕获异常,但我仍然收到错误:

<br />
<b>Fatal error</b>:  Uncaught Transmission\Exception\NetworkException: 403: Forbidden - Your IP Address is Not Whitelisted in /php-transmission-sdk/src/Exception/NetworkException.php:82
Stack trace:
#0 /php-transmission-sdk/src/HttpClient/Plugin/ExceptionThrower.php(44): Transmission\Exception\NetworkException::createByCode(403, '403: Forbidden ...')
#1 /php-transmission-sdk/vendor/php-http/httplug/src/Promise/HttpFulfilledPromise.php(34): Transmission\HttpClient\Plugin\ExceptionThrower-&gt;Transmission\HttpClient\Plugin\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /php-transmission-sdk/src/HttpClient/Plugin/ExceptionThrower.php(48): Http\Client\Promise\HttpFulfilledPromise-&gt;then(Object(Closure))
#3 /php-transmission-sdk/vendor/php-http/client-common/src/PluginClient.php(132): Transmission\HttpClient\Plugin\ExceptionThrower-&gt;handleRequest(Object(Nyholm\Psr7\Request), O in <b>/php-transmission-sdk/src/Exception/NetworkException.php</b> on line <b>82</b><br />

NetworkException.php

<?php

namespace Transmission\Exception;

/**
 * NetworkException
 */
class NetworkException extends \Exception
{
    public const CONFLICT = 409;

    public static $statusCodes = [
        // 4xx: Client Error - The request contains bad syntax or cannot be fulfilled.
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Payload Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'I\'m a teapot',
        421 => 'Misdirected Request',
        422 => 'Unprocessable Entity',
        423 => 'Locked',
        424 => 'Failed Dependency',
        426 => 'Upgrade Required',
        428 => 'Precondition Required',
        429 => 'Too Many Requests',
        431 => 'Request Header Fields Too Large',
        444 => 'Connection Closed Without Response',
        451 => 'Unavailable For Legal Reasons',
        499 => 'Client Closed Request',

        // 5xx: Server Error - The server failed to fulfill an apparently valid request.
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',
        507 => 'Insufficient Storage',
        508 => 'Loop Detected',
        510 => 'Not Extended',
        511 => 'Network Authentication Required',
        599 => 'Network Connect Timeout Error',
    ];

    /**
     * Create Exception by Network Code.
     *
     * @param int         $statusCode
     * @param null|string $message
     *
     * @return static
     */
    public static function createByCode(int $statusCode, string $message = null): self
    {
        $errorMessage = null;
        if (isset(static::$statusCodes[$statusCode])) {
            $errorMessage = static::$statusCodes[$statusCode];

            if (filled($message)) {
                $errorMessage = $errorMessage . ' - ' . $message;
            }
        }


        $message = sprintf('%d: %s', $statusCode, $errorMessage ?? $message);

        return new static($message, $statusCode);
    }
}

回购:https://github.com/irazasyed/php-transmission-sdk

PHP 7.3.11

【问题讨论】:

  • 您的代码是否也在命名空间中?
  • 我只有require 'vendor/autoload.php'; use Transmission\Exception;
  • 也许您试图在另一个地方捕获异常?
  • 尝试替换 NetworkException on Exception 并检查。

标签: php transmission


【解决方案1】:

您正在使用相对命名空间在 catch 语句中定义异常 Transmission\Exception\NetworkException $e

要么简单地使用NetworkException,要么在前面添加一个反斜杠以使其成为完全限定的引用。

编辑: 来自 php 文档的参考 https://www.php.net/manual/en/language.namespaces.basics.php

编辑:澄清解决方案

要么

try
{...}
catch (NetworkException $e)
{ ... }

try
{...}
catch (\Transmission\Exception\NetworkException $e)
{ ... }

【讨论】:

  • 你能准确地显示我需要放什么吗?我用了} catch (\NetworkException $e) {,但还是同样的错误
  • 谢谢,我都试过了,但不幸的是我仍然遇到同样的错误
  • @executable 如果直接在“try”块中抛出异常,使用throw new NetworkException("test",400) 会被捕获吗?我之所以问,是因为您生成实例的方式可能会发生一些意想不到的事情 (new static(...))
  • 如果我在try 块中添加throw new NetworkException("test",400); 并捕获} catch (\NetworkException $e) { 我有以下错误&lt;b&gt;Fatal error&lt;/b&gt;: Uncaught Transmission\Exception\NetworkException: test in path/to/my/file.php:19 Stack trace: #0 {main} thrown in &lt;b&gt;/path/to/my/file.php&lt;/b&gt; on line &lt;b&gt;19&lt;/b&gt;&lt;br /&gt;
  • @executable 去掉 catch 语句中 NetworkException 前的 `\`
【解决方案2】:

由于您没有use-statement for NetworkException,PHP 将假定它应该从您当前正在操作的命名空间中加载。(大概是 \。)要解决这个问题,只需添加像use Transmission\Exception\NetworkException; 这样的声明。这将告诉 PHP 你试图捕获什么类型的异常。

【讨论】:

  • 我添加了use Transmission\Exception\NetworkException; 并使用} catch (NetworkException $e) { 之类的catch 我仍然收到错误:(
【解决方案3】:

我是这样解决的:

<?php
require 'vendor/autoload.php';
try{
    $transmission = new Transmission\Client($hostname, $port, $username, $password, $httpClientBuilder = null);
} catch (Transmission\Exception\NetworkException $e) {
    $result = array("Error" => "Remote access is disabled");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    相关资源
    最近更新 更多