wellrested/http-exceptions

一组与常见HTTP错误状态码对应的异常

v1.0.0 2015-05-30 13:03 UTC

This package is auto-updated.

Last update: 2024-09-12 07:11:53 UTC


README

HttpException 及其子类提供与HTTP错误状态码相对应的异常。包含最常见的异常,但您可以通过使用(或继承)HttpException 并将原因短语作为 $message,将状态码作为 $code 来创建其他状态码的异常。

此包在 WellRESTed\HttpExceptions 命名空间中提供了以下异常类。

基本用法

抛出异常。

throw new \WellRESTed\HttpExceptions\UnauthorizedException(); 

抛出自定义异常,提供状态码。

throw new \WellRESTed\HttpExceptions\HttpException(
    "HTTP Version Not Supported", 505); 

捕获异常并输出HTML响应。

try {
    // ... 
} catch (\WellRESTed\HttpExceptions\HttpException $e) {
    http_response_code($e->getCode());
    header("Content-type: text/html");
    print "<h1>" . $e->getCode()  . " " . $e->getMessage() . "</h1>";
}

或者,如果您使用的是 WellRESTed

try {
    // ... 
} catch (\WellRESTed\HttpExceptions\HttpException $e) {
    $response = $response
        ->withStatus($e->getCode())
        ->withHeader("Content-type", "text/html")
        ->withBody(new \WellRESTed\Message\Stream(
            "<h1>" . $e->getCode()  . " " . $e->getMessage() . "</h1>"));
}

安装

wellrested/http-exceptions 添加到您的 composer.json 文件中

{
    "require": {
        "wellrested/http-exceptions": "^1.0"
    }
}

版权和许可

版权所有 © 2015 by PJ Dietz。许可协议为 MIT 许可协议