流结构化错误

StreamErrorMode::Error|Exception|Silent; StreamException::getErrors(): array; StreamError->code: StreamErrorCode; StreamError->wrapperName: string; stream_last_errors(): array; stream_clear_errors(): void

PHP 8.6 流错误处理族:error_mode 上下文选项让流失败改为抛 StreamException 或静默——错误变成 StreamErrorCode 枚举 + wrapperName + 路径的结构化对象,「警告字符串」时代落幕。

C C23

C23
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    FILE *f = fopen("/definitely/not/here/a55.txt", "r");
    if (f == NULL) {
        /* errno 是全局 int 不是对象:消息经 strerror 查表,
           没有可以 switch 的错误码枚举。 */
        printf("code=ENOENT:%d\n", errno == ENOENT);
        printf("msg=%s\n", strerror(errno));
    }
    return 0;
}
输出
code=ENOENT:1
msg=No such file or directory

C++ C++26

C++26
#include <cstdio>
#include <system_error>

int main() {
    std::error_code ec; // 结构化:值 + 类别,但形状仍是 errno
    FILE *f = fopen("/definitely/not/here/a55.txt", "r");
    if (f == nullptr) {
        ec = std::error_code(errno, std::system_category());
        std::printf("kind=%d\n", ec == std::errc::no_such_file_or_directory);
        std::printf("value=%d\n", ec.value());
    } else {
        std::fclose(f);
    }
    return 0;
}
输出
kind=1
value=2

C# v11.0.100

v11.0.100
using System;
using System.IO;

try
{
    File.OpenRead("/definitely_not_here_a55.txt"); // 不缺中间目录
}
catch (FileNotFoundException e)
{
    Console.WriteLine(e.GetType().Name);
    Console.WriteLine(e.FileName.Contains("a55.txt"));
}
catch (IOException e)
{
    Console.WriteLine("io: " + e.GetType().Name);
}
输出
FileNotFoundException
True

Go v1.27.4

v1.27.4
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

func main() {
	_, err := os.Open("/definitely/not/here/a55.txt")
	if err != nil {
		// 每个错误都是实现 error 接口的值;errors.Is/As
		// 无需触碰消息字符串即可解构。
		fmt.Println(errors.Is(err, fs.ErrNotExist))
		var perr *fs.PathError
		fmt.Println(errors.As(err, &perr))
		fmt.Println(perr.Op)
	}
}
输出
true
true
open

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) {
        try {
            Files.newInputStream(Path.of("/definitely/not/here/a55.txt"));
        } catch (NoSuchFileException e) {
            // 类型化异常:类名 + 路径,无需解析字符串
            System.out.println(e.getClass().getSimpleName());
            System.out.println(e.getMessage().contains("a55.txt"));
        } catch (IOException e) {
            System.out.println("other: " + e.getClass().getSimpleName());
        }
    }
}
输出
NoSuchFileException
true

JavaScript v26.13.1

v26.13.1
const fs = require('node:fs');
try {
  fs.readFileSync('/definitely/not/here/a55.txt');
} catch (e) {
  console.log(e instanceof Error);
  console.log(e.code);   // 结构化错误码字符串,不是警告
  console.log(e.errno === -2); // libuv 的 ENOENT
  console.log(e.path === '/definitely/not/here/a55.txt');
}
输出
true
ENOENT
true
true

PHP v8.6.0

v8.6.0
// Exception 模式:流失败改为抛 StreamException 而非警告
$ctx = stream_context_create([
    'stream' => ['error_mode' => StreamErrorMode::Exception],
]);
try {
    fopen('/definitely/not/here/a55.txt', 'r', false, $ctx);
    var_dump(false);
} catch (StreamException $e) {
    $errs = $e->getErrors();
    var_dump(count($errs) === 1);
    var_dump($errs[0]->code === StreamErrorCode::OpenFailed);
    var_dump($errs[0]->code->name);
    var_dump(is_string($errs[0]->message) && $errs[0]->message !== '');
    var_dump($errs[0]->terminating);
}

// Silent 模式:返回 false + 错误留存供 stream_last_errors() 查阅
$ctx2 = stream_context_create([
    'stream' => ['error_mode' => StreamErrorMode::Silent],
]);
var_dump(fopen('/definitely/not/here/a55.txt', 'r', false, $ctx2) === false);
$stored = stream_last_errors();
var_dump(count($stored) === 1);
var_dump($stored[0]->code === StreamErrorCode::OpenFailed);
输出
bool(true)
bool(true)
string(10) "OpenFailed"
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Python v3.15.2

v3.15.2
try:
    f = open("/definitely/not/here/a55.txt", "r")
except OSError as e:
    print(type(e).__name__)
    print(e.errno == 2)  # 结构化错误码,不是警告字符串
    print(e.strerror == "No such file or directory")
else:
    f.close()
输出
FileNotFoundError
True
True

Rust v1.99.1

v1.99.1
use std::io::ErrorKind;

fn main() {
    match std::fs::File::open("/definitely/not/here/a55.txt") {
        Err(e) => {
            println!("{}", e.kind() == ErrorKind::NotFound);
            println!("{}", e.raw_os_error() == Some(2)); // ENOENT
        }
        Ok(_) => println!("opened"),
    }
}
输出
true
true

TypeScript v26.13.1

v26.13.1
import * as fs from 'node:fs';
// 类型化错误把 code/errno/path 当一等字段携带
try {
  fs.readFileSync('/definitely/not/here/a55.txt');
} catch (e) {
  const err = e as NodeJS.ErrnoException;
  console.log(err instanceof Error);
  console.log(err.code);
  console.log(err.errno === -2);
  console.log(err.path === '/definitely/not/here/a55.txt');
}
输出
true
ENOENT
true
true

语言差异说明

C:errno 全局 int + strerror 查表(示例):错误是进程级全局变量,无对象无枚举,多线程要 errno per thread 兜底;对照核心——C 的「结构化」只有整数码一层。

C++:std::error_code(示例):值 + category 二元组是介于 errno 与异常之间的结构化中间态;std::errc 提供可移植枚举(no_such_file_or_directory ≙ OpenFailed 的对应层级),但仍无 wrapperName/path 这类流语境字段。

C#:FileNotFoundException/DirectoryNotFoundException/IOException 异常族(示例):类型即分类(GetType().Name),FileName 字段携带路径——结构化程度与 StreamError 相当;catch 链从特化到泛化的顺序就是 StreamErrorCode 枚举想统一表达的事。

Go:error 接口值(示例):os.Open 返回 *fs.PathError{Op, Path, Err} 三字段结构体——Op(open)↔ wrapperName、Path ↔ path、Err ↔ code;errors.Is/As 解构不碰消息串,是「结构化 vs 字符串」的经典示范。

Java:NoSuchFileException 等类型化异常(示例):FileSystemException 携带 file/other 字段;catch NoSuchFileException → IOException 的分级捕获与 StreamErrorCode 枚举的粒度思路同源。

JavaScript:Error 子类 + code/errno/path 属性(示例):ENOENT 字符串码 + libuv 负数 errno;JS 生态的异构错误(字符串/Error/undefined)正是 PHP 警告字符串困境的镜像,结构化属性是 Node 从第一天就做对的部分。

PHP:8.6 RFC stream_errors(示例):stream 上下文的 error_mode 三态——Error(默认警告,PHP 5.x 起的旧世界)、Exception(抛 StreamException,getErrors() 返 StreamError 列表)、Silent(返回 false,错误留存供 stream_last_errors(),stream_clear_errors() 清空);StreamError 对象携带 code(StreamErrorCode 枚举,OpenFailed/ConnectFailed/TimeOut 等数十项)+ message + wrapperName + path/URL + severity + terminating;error_get_last(对照)只给 type/message/file/line 通用四件套,流语境信息全靠正则拆字符串——本条把「警告字符串 → 结构化对象」的演进补完。

Python:OSError 异族(示例):open 触发 FileNotFoundError(OSError 子类),errno==2(POSIX ENOENT)+ strerror 双结构化字段;异常层级(OSError → FileNotFoundError/PermissionError/…)与 StreamErrorCode 枚举是同一分类学的两种实现。

Rust:io::Error(示例):ErrorKind::NotFound 跨平台枚举 + raw_os_error() 保留原始码——「可移植枚举 + 平台原码」双层与 StreamErrorCode + severity 的分工同构;Result 强制处理使「漏看警告」这类事在类型上不可能。

TypeScript:同 JS(示例):NodeJS.ErrnoException 接口把 code?: string、errno?: number、path?: string 写进类型——结构化字段的类型化契约,让 e.code !== 'ENOENT' 的判断有编译期检查。