使用 try/catch 不捕获异常

Use try/catch doesn't catch the exception

我有以下代码:

<?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

您正在使用相对命名空间在 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)
{ ... }

由于您没有 NetworkExceptionuse 语句,PHP 将假定它应该从您当前正在操作的名称空间中加载。(大概 \.) 要解决此问题,只需添加 use Transmission\Exception\NetworkException; 之类的语句即可。这将告诉 PHP 您要捕获的异常类型。

我是这样解决的:

<?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");
}