【问题标题】:PHP catching thrown InvalidArgumentException from functionPHP从函数中捕获抛出的InvalidArgumentException
【发布时间】:2020-10-24 22:35:18
【问题描述】:

我正在使用 JWS 库来取消对某些令牌的签名,所以当令牌无效时,我得到了异常 InvalidArgumentException

({ "name": "Exception", "message": "令牌 \"123\" 是无效的 JWS", "code": 0, "type": "InvalidArgumentException", "file": " /var/www/html/checkout/vendor/namshi/jose/src/Namshi/JOSE/J‌​WS.php", "line": 143,)

$jws= SimpleJWS::load($data);

如果令牌无效,静态函数加载会引发异常,我不想显示异常消息,而是希望显示友好的错误消息。

有什么帮助吗?

【问题讨论】:

  • 只需使用try{} catch(invalidArgumentException $e ){}
  • 我试过这个尝试 {$jws= SimpleJWS::load($data);}catch(invalidArgumentException $e){echo $e->getMessage();} 但不起作用!

标签: php


【解决方案1】:

这个呢:

try {
    $jws= SimpleJWS::load($data);
// if it's the php exception http://php.net/manual/en/class.invalidargumentexception.php
} catch (\InvalidArgumentException $e) {
// if it's the library's exception you should specify the complete namespace
//} catch (InvalidArgumentException $e) {
    //  token is not valid
} 

【讨论】:

  • 仍然无法正常工作 ({ "name": "Exception", "message": "The token \"123\" is an invalid JWS", "code": 0, "type": " InvalidArgumentException", "file": "/var/www/html/checkout/vendor/namshi/jose/src/Namshi/JOSE/JWS.php", "line": 143,)
  • 谢谢你,但是为什么“\Exception”这个工作不是“InvalidArgumentException”,因为抛出的异常是InvalidArgumentException?
  • 您的文件位于命名空间中,因此您需要使用\InvalidArgumentException 来捕获基本命名空间的异常。如果忘记了名称前的'\',php 将查找当前命名空间中定义的 InvalidArgumentException
【解决方案2】:

试试这个,它对我有用

try {
    $jws= SimpleJWS::load($data);
} catch (\Exception $e) {
    # Do something
} 

【讨论】:

    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2018-03-08
    • 2018-08-09
    • 2020-03-08
    • 2016-11-03
    • 2015-06-29
    相关资源
    最近更新 更多