【问题标题】:in PHP, which Exception codes are mapped to http status codes?在 PHP 中,哪些异常代码映射到 http 状态代码?
【发布时间】:2017-09-09 14:17:22
【问题描述】:

我正在开发一个 (CakePHP) Web 应用程序,从而创建自己的异常类。

目前我尝试创建一个锁定异常,该异常应返回 HTTP 状态代码 423(已锁定):

<?php
namespace App\Exceptions;

use Cake\Network\Exception\HttpException;

class MeasuringPointLockedException extends HttpException{   
    /**
     * Constructor
     *
     * @param string $message If no message is given 'Locked' will be the message
     */
    public function __construct($message = 'Locked'){   
        parent::__construct($message, 422);
    }
}    
?>

不幸的是,在某些时候我的代码 423 被消耗并替换为 500(内部服务器错误)。我注意到,只有一些代码被替换,其他代码(如 400、404、422)被传递。

注意:HttpException 是 PHP 内置异常的扩展。

我注意到,在这两者之间,响应代码 423 用于 WebDAV 服务,但是:

是否有任何文档,通过哪些代码?在抛出(而不是捕获)这样的异常时,我怎样才能达到 status = 423?

【问题讨论】:

  • \Cake\Http\Response::$_statusCodes 中定义的所有介于 400 和 506 之间的代码都可以通过 HTTP 异常设置,所有其他代码都会设置为 500。我建议您启用调试或检查日志以确保没有发生与您预期不同的错误,同时检查 github.com/cakephp/cakephp/issues/8962。请务必提及您的 准确 CakePHP 版本(vendor/cakephp/cakephp/VERSION.txt 中的最后一行)- 谢谢!
  • 我正在使用 Cake 3.3.1。好的,我查看了 cakephp/cakephp/src/Network/Response.php 并找到了代码。无论如何,有没有办法克服这个过滤器并通过异常传递其他状态代码?在此先感谢 ;)

标签: php exception cakephp-3.0 http-status-codes


【解决方案1】:

您可以在这里看到一堆 http 异常: [https://book.cakephp.org/3/en/development/errors.html1

这里也是一个很好的例子来说明如何实现这个:

use Cake\Core\Exception\Exception;

class MissingWidgetException extends Exception
{
    // Set your message here
    protected $_messageTemplate = 'Your message';

    // Set your status code here
    protected $_defaultCode = 404;
}

throw new MissingWidgetException(['widget' => 'Pointy']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2010-12-10
    • 2021-12-14
    • 2011-01-23
    相关资源
    最近更新 更多