0

0

快速失败

霞舞

霞舞

发布时间:2024-12-04 08:27:32

|

998人浏览过

|

来源于dev.to

转载

快速失败

核心原则

故障发生后立即检测并报告,防止无效状态在系统中传播。

1. 输入验证

class userregistration {
    public function register(array $data): void {
        // validate all inputs immediately
        $this->validateemail($data['email']);
        $this->validatepassword($data['password']);
        $this->validateage($data['age']);

        // only proceed if all validations pass
        $this->createuser($data);
    }

    private function validateemail(string $email): void {
        if (!filter_var($email, filter_validate_email)) {
            throw new validationexception('invalid email format');
        }
        if ($this->emailexists($email)) {
            throw new duplicateemailexception('email already registered');
        }
    }
}

目的:

爱设计PPT
爱设计PPT

AI快速生成高质量PPT

下载
  • 防止无效数据进入系统
  • 通过在复杂操作之前失败来节省资源
  • 向用户提供清晰的错误消息
  • 维护数据完整性

2. 配置加载

class appconfig {
    private array $config;

    public function __construct(string $configpath) {
        if (!file_exists($configpath)) {
            throw new configurationexception("config file not found: $configpath");
        }

        $config = parse_ini_file($configpath, true);
        if ($config === false) {
            throw new configurationexception("invalid config file format");
        }

        $this->validaterequiredsettings($config);
        $this->config = $config;
    }

    private function validaterequiredsettings(array $config): void {
        $required = ['database', 'api_key', 'environment'];
        foreach ($required as $key) {
            if (!isset($config[$key])) {
                throw new configurationexception("missing required config: $key");
            }
        }
    }
}

目的:

  • 确保应用程序以有效配置启动
  • 防止由于缺少设置而导致运行时错误
  • 使配置问题立即可见
  • 简化调试配置问题

3. 资源初始化

class databaseconnection {
    private pdo $connection;

    public function __construct(array $config) {
        try {
            $this->validatedatabaseconfig($config);
            $this->connection = new pdo(
                $this->builddsn($config),
                $config['username'],
                $config['password'],
                [pdo::attr_errmode => pdo::errmode_exception]
            );
        } catch (pdoexception $e) {
            throw new databaseconnectionexception(
                "failed to connect to database: " . $e->getmessage()
            );
        }
    }

    private function validatedatabaseconfig(array $config): void {
        $required = ['host', 'port', 'database', 'username', 'password'];
        foreach ($required as $param) {
            if (!isset($config[$param])) {
                throw new databaseconfigexception("missing $param in database config");
            }
        }
    }
}

目的:

  • 确保资源正确初始化
  • 防止应用程序使用无效资源运行
  • 使资源问题在启动期间可见
  • 避免由于无效资源导致的级联失败

4. 外部服务调用

class paymentgateway {
    public function processpayment(order $order): paymentresult {
        // validate api credentials
        if (!$this->validateapicredentials()) {
            throw new apiconfigurationexception('invalid api credentials');
        }

        // validate order before external call
        if (!$order->isvalid()) {
            throw new invalidorderexception('invalid order state');
        }

        try {
            $response = $this->apiclient->charge($order);

            if (!$response->issuccessful()) {
                throw new paymentfailedexception($response->geterror());
            }

            return new paymentresult($response);
        } catch (apiexception $e) {
            throw new paymentprocessingexception(
                "payment processing failed: " . $e->getmessage()
            );
        }
    }
}

目的:

  • 防止使用无效数据进行不必要的 api 调用
  • 节省时间和资源
  • 提供有关 api 问题的即时反馈
  • 在外部服务交互期间保持系统可靠性

5. 数据处理管道

class DataProcessor {
    public function processBatch(array $records): array {
        $this->validateBatchSize($records);

        $results = [];
        foreach ($records as $index => $record) {
            try {
                $this->validateRecord($record);
                $results[] = $this->processRecord($record);
            } catch (ValidationException $e) {
                throw new BatchProcessingException(
                    "Failed at record $index: " . $e->getMessage()
                );
            }
        }

        return $results;
    }

    private function validateBatchSize(array $records): void {
        if (empty($records)) {
            throw new EmptyBatchException('Empty batch provided');
        }

        if (count($records) > 1000) {
            throw new BatchSizeException('Batch size exceeds maximum limit');
        }
    }
}

目的:

  • 确保整个处理过程中的数据一致性
  • 防止部分处理无效数据
  • 尽早发现数据问题
  • 简化复杂管道中的错误跟踪
  • 在转换过程中保持数据完整性

快速失败的好处

  1. 早期错误检测
  2. 更干净的调试
  3. 防止级联故障
  4. 维护数据完整性
  5. 提高系统可靠性

最佳实践

  1. 使用强类型声明
  2. 实施彻底的输入验证
  3. 抛出特定异常
  4. 在流程的早期进行验证
  5. 在开发中使用断言
  6. 实施正确的错误处理
  7. 适当记录失败

何时使用快速失败

  1. 输入验证
  2. 配置加载
  3. 资源初始化
  4. 外部服务电话
  5. 数据处理管道

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

43

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

35

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

204

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

8

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号