【问题标题】:How to throw NotFoundResourceException with code status code 404 in Laravel如何在 Laravel 中使用代码状态码 404 抛出 NotFoundResourceException
【发布时间】:2021-06-22 14:18:52
【问题描述】:

我正在尝试以编程方式在 Laravel 中抛出 NotFoundResourceException

  use Symfony\Component\Translation\Exception\NotFoundResourceException;
  
  throw new NotFoundResourceException('The Item you could not be found', 404);

从代码编辑器中,我可以看到第二个参数是代码的提示,但这会返回状态 500 而不是 404

throw new NotFoundResourceException('The Item you could not be found');不带参数也返回状态500

我可以按照How to make Laravel 5 return 404 status code 中的建议使用abort(404),但是有没有办法解决throw 404 错误?

【问题讨论】:

  • abort() 意味着它抛出并中止所有操作

标签: php laravel


【解决方案1】:

看起来你导入了错误的NotFoundResourceException 而不是NotFoundHttpException

NotFoundResourceException 扩展自 Exception

public function __construct($message = "", 
                            $code = 0,
                           Throwable $previous = null
                          ) 

所以它不会抛出http异常。

如果您查看从 HttpException 扩展而来的 NotFoundHttpException 的实现,构造函数有

     public function __construct(?string $message = '', 
                                  \Throwable $previous = null, 
                                   int $code = 0, 
                                   array $headers = []
                                 )

所以它接受第二个参数为$previous exception

try {
        test();
    } catch(Error $e) {

        throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException("not found pagew",$e,404);
    }

现在如果我们在App\Exceptions\Handler 中发现错误

public function render($request, Throwable $e)
    {
        if($e instanceof NotFoundHttpException){
            dump($e->getMessage());
            dump($e->getCode());
            dd($e->getPrevious());

        }

        return parent::render($request, $e); // TODO: Change the autogenerated stub
    }

它会像下面这样打印

“未找到页面”

404

错误 {#353 ▼ #message: "Call to undefined function test()" #code: 0 #file: "I:\xampp\htdocs\adbs\live\sra\routes\web.php" #line: 28 追踪:{▶} }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    相关资源
    最近更新 更多