rumd3x/php-go-errors

PHP 实现的 golang errors 包。

1.0.0 2019-07-11 03:55 UTC

This package is auto-updated.

Last update: 2024-09-13 09:18:43 UTC


README

PHP 实现的 golang errors 包。

Build Status Codecov PHP Version

安装

composer require rumd3x/php-go-errors

示例

以下是一个使用标准 Error 实现的示例。

更多详细信息,请参阅下方的 API 文档。

<?php
require 'vendor/autoload.php';

use Rumd3x\Errors\Error;


$result = exampleFunction();

if ($result instanceof Error) {
    echo "$result\n";
    exit 1;
}

echo "File contents:\n";
foreach ($data as $row) {
    echo "$row\n";
}

/**
 * The example function
 */
function exampleFunction() {
    $data = file('filename.txt');

    if ($data === false) {
        return Error::new('failed to open file');
    }

    return $data;
}

API

此库提供两个工具,可以扩展使用:

  • 标准接口:Rumd3x\Errors\ErrorInterface
  • 标准实现:Rumd3x\Errors\Error,它已经实现了 Rumd3x\Errors\ErrorInterface

Error (接口)

Rumd3x\Errors\ErrorInterface 实现的构造函数应接受错误信息字符串作为其第一个和唯一参数。

$err = new ErrorImplementation('error message');

它还应提供一个公共方法 error 将实例转换为错误信息

$err = new ErrorImplementation('error message');
echo $err->error();

Error (实现)

标准错误实现的完整类名为 Rumd3x\Errors\Error,并且已经实现了 Rumd3x\Errors\ErrorInterface

  • 此库中包含的标准错误实现不是最终的,因此可以扩展。
  • 它也可以安全地视为字符串。

它还提供了以下额外的方法

  • new (静态)
  • newf (静态)

new

new 方法允许创建一个新的错误实例,但静态地,它和构造函数的功能相同。

$err = Error::new('error message');

newf

newf 方法允许创建一个新的错误实例,但它可以接受无限数量的参数:(它和格式化字符串使用 sprintf 然后传递给 new 方法在功能上是相同的)

  • 第一个参数应该是错误文本,但它接受 % 格式化符号;
  • 其余参数应该是要格式化到错误文本中的参数;
$err = Error::newf('error: %d is %s than %d', 10, 'less', 20);

将错误视为字符串

Rumd3x\Errors\Error 或任何扩展它的类都可以安全地视为字符串,并一起使用。

$err = Error::new('error message');
$text = $error->error(); // $text should contain 'error message'
$text2 = (string) $error; // $text2 should also contain 'error message'
echo $err; // should output 'error message'
echo "Error: $err"; // should output 'Error: error message'