告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好

告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好

在项目开发中,我曾多次遇到这样的困境:后端API使用opis/json-schema进行严格的数据验证,这很好地保证了数据的质量。但一旦验证失败,返回给客户端的错误信息通常是像{"keyword": "minLength", "pointer": "productName", "message": "The Attribute length should be at least 3 characters."}这样的原始技术细节。对于普通用户来说,这些信息过于专业和晦涩,无法提供直观的指引。为了将这些机器友好的错误转化为人类可读的、甚至本地化的提示,我不得不编写大量的转换逻辑,这不仅耗时,也使得代码变得臃肿且难以维护。

composer在线学习地址:学习地址

幸运的是,php社区的强大之处在于总有开发者为我们解决痛点。今天,我要向大家介绍一个非常实用的Composer包:m1x0n/opis-json-schema-Error-presenter

重要提示: 需要注意的是,opis/json-schema库的最新版本(2.0.0及以上)可能已经内置了错误格式化功能,这意味着m1x0n/opis-json-schema-error-presenter在未来可能会变得不那么必要。但对于目前正在使用旧版本opis/json-schema,或者需要更高度定制化错误呈现方式的项目来说,这个库仍然是不可多得的利器。

m1x0n/opis-json-schema-error-presenter是一个专门用于将OpisJsonSchemaValidationError对象转换为人类可读的、结构化的错误信息的库。它让我们可以轻松地将那些冰冷的验证失败信息,转化为用户友好的提示,极大地提升了用户体验和开发效率。

如何使用 Composer 解决问题

首先,通过Composer安装这个库:

告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好

Find JSON Path Online

Easily find JSON paths within JSON objects using our intuitive Json Path Finder

告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好 30

查看详情 告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-json-schema-error-presenter让错误信息更友好

<code class="bash">composer require m1x0n/opis-json-schema-error-presenter</code>

安装完成后,你可以像下面这样使用它来美化你的验证错误:

<pre class="brush:php;toolbar:false;"><?php  require __DIR__ . '/vendor/autoload.php';  use OpisJsonSchemaSchema; use OpisJsonSchemaValidator; use OpisErrorPresenterImplementationMessageFormatterFactory; use OpisErrorPresenterImplementationPresentedValidationErrorFactory; use OpisErrorPresenterImplementationValidationErrorPresenter; use OpisErrorPresenterContractsPresentedValidationError;  // 假设你的JSON Schema和待验证数据 $jsonSchema ='{   "$schema": "http://json-schema.org/draft-07/schema#",   "title": "Product",   "type": "object",   "properties": {     "productId": { "type": "integer", "minimum": 1 },     "productName": { "type": "string", "minLength": 3 },     "price": {       "type": "object",       "properties": {         "amount": { "type": "integer", "minimum": 0, "maximum": 1000 },         "currency": { "type": "string", "enum": ["USD", "EUR", "BTC"] }       },       "required": ["amount", "currency"]     }   },   "required": [ "productId", "productName", "price" ] }';  $data = '{   "productId": "123", // 期望整数,实际字符串   "productName": "XX", // 期望最小长度3,实际2   "price": {     "amount": 200,     "currency": "GBP" // 期望USD/EUR/BTC,实际GBP   } }';  $data = json_decode($data); $jsonSchema = Schema::fromJsonString($jsonSchema); $validator = new Validator();  // 获取所有验证错误 $result = $validator->schemaValidation($data, $jsonSchema, -1); // -1 表示获取所有错误  if (!$result->isValid()) {     // 使用 ValidationErrorPresenter 来格式化错误     $presenter = new ValidationErrorPresenter(         new PresentedValidationErrorFactory(             new MessageFormatterFactory()         )     );      // 呈现错误     $presentedErrors = $presenter->present(...$result->getErrors());      // 输出格式化后的错误     echo "验证失败,错误信息如下:n";     foreach ($presentedErrors as $error) {         /** @var PresentedValidationError $error */         echo "- 字段: " . $error->getPointer() . "n";         echo "  问题: " . $error->getMessage() . "n";         echo "  关键词: " . $error->getKeyword() . "n";         echo "---------------------------n";     }      // 也可以直接转换为JSON格式输出     echo "nJSON格式错误输出:n";     echo json_encode(array_map(static function (PresentedValidationError $error) {         return $error->toArray();     }, $presentedErrors), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else {     echo "数据验证通过!n"; }

上述代码的输出示例:

<pre class="brush:php;toolbar:false;">验证失败,错误信息如下: - 字段: productId   问题: The attribute expected to be of type 'integer' but 'string' given.   关键词: type --------------------------- - 字段: productName   问题: The attribute length should be at least 3 characters.   关键词: minLength --------------------------- - 字段: price/currency   问题: The attribute must be one of the following values: 'USD', 'EUR', 'BTC'.   关键词: enum ---------------------------  JSON格式错误输出: [     {         "keyword": "type",         "pointer": "productId",         "message": "The attribute expected to be of type 'integer' but 'string' given."     },     {         "keyword": "minLength",         "pointer": "productName",         "message": "The attribute length should be at least 3 characters."     },     {         "keyword": "enum",         "pointer": "price/currency",         "message": "The attribute must be one of the following values: 'USD', 'EUR', 'BTC'."     } ]

优势与实际应用效果

  1. 用户体验大幅提升: 将技术错误转化为易懂的提示,用户能迅速理解问题并修正,无论是表单验证还是API响应,都能提供更友好的反馈。
  2. 开发效率提高: 前端或API消费者无需再手动解析复杂的错误结构,直接使用格式化后的信息,减少了客户端的开发负担。
  3. 国际化支持: 该库支持自定义翻译和多语言。你可以为不同的验证关键字定义专属的、本地化的错误消息,轻松实现多语言错误提示,满足全球化应用的需求。
  4. 高度可定制: 你可以定义不同的错误呈现策略(例如,只显示第一个错误、显示所有错误或最佳匹配错误),也可以完全自定义错误消息的格式和内容,根据业务需求调整错误信息的呈现方式。
  5. 代码更整洁: 将错误呈现逻辑从核心业务逻辑中分离,提高了代码的可维护性和可读性。

告别那些令人头疼的、机器友好的验证错误吧!m1x0n/opis-json-schema-error-presenter为我们提供了一个优雅而强大的解决方案,让你的应用程序能够以更清晰、更友好的方式与用户沟通。如果你正在使用opis/json-schema且需要优化错误呈现,不妨尝试一下这个实用的Composer包!

以上就是告别晦涩难懂的JSON验证错误:使用Composer包m1x0n/opis-

上一篇
下一篇
text=ZqhQzanResources