序言
不管是微博还是淘宝,他们都有自己的错误返回值格式规范,以及错误代码说明,这样不但手机端用起来方便,给人的感觉也清晰明了,高大上。遇到问题先找母本,大公司的规范就是我们参照的母本。为此,我仿照了淘宝的错误返回值格式,根据微博错误代码制定的标准自定了自己的错误代码,然后在Restful api 上进行测试。下面我将实现思路以及测试结果分享给大家。
实现思路
我利用抽象工厂模式去实现这样的一个错误返回值。选择这种模式是因为考虑到了这种模式可以提供一个创建一系列相关或相互依赖对象的接口,与我的需求很接近。
代码分析
1、按这个路径common\hint,我新建了个error文件夹存放我的错误提示程序文件。这文件夹中主要有这几个文件:
2、Hint.php入口文件。定义一个抽象类,里边只写一个方法。
interface Hint { function Error($_errors,$code);}
3、Template.php 实现Hint这个接口。错误返回值的格式就在这里定义。
class Template implements Hint{ function Error($_errors,$code) { if (empty($_errors)) { print_r(json_encode([])); } else { $errors['error']['name'] = 'Not Found'; $errors['error']['message'] = $_errors; $errors['error']['error_code'] = $code; print_r(json_encode($errors)); } }}
4、createMsg.php 再创建一个createMsg抽象类。将对象的创建抽象成一个接口。
interface createMsg { function Msg(); }
5、用FactoryMsg 类去实现createMsg接口。返回实例化的Template。
class FactoryMsg implements createMsg{ function Msg() { return new Template; }}
6、ErrorMsg.php 给Template里边的Error方法传参。
class ErrorMsg { // 抽象工厂里的静态方法 public static function Info($_errors) { $Factory = new FactoryMsg; $result = strstr($_errors,Yii::t('yii','Not exist')); //数据不存在 20001 $result1 = strstr($_errors,Yii::t('yii','Null')); //参数不能为空 20002 $result2 = strstr($_errors,Yii::t('yii','Fail')); //新增、更新、删除失败 20003 $result3 = strstr($_errors,Yii::t('yii','Not right')); //XX不正确 20004 $result4 = strstr($_errors,Yii::t('yii','Robc')); //XX无权限 20005 //数据不存在 20001 if(!empty($result)){ $M = $Factory->Msg(); $M->Error($_errors,'20001');die; } //参数不能为空 20002 if(!empty($result1)){ $M = $Factory->Msg(); $M->Error($_errors,'20002');die; } //新增、更新、删除失败 20003 if(!empty($result2)){ $M = $Factory->Msg(); $M->Error($_errors,'20003');die; } //XX不正确 20004 if(!empty($result3)){ $M = $Factory->Msg(); $M->Error($_errors,'20004');die; } //XX无权限 20005 if(!empty($result4)){ $M = $Factory->Msg(); $M->Error($_errors,'20005');die; } //默认类型 21000 $M = $Factory->Msg(); $M->Error($_errors,'21000'); }}
7、调用方式。
use common\hint\error\ErrorMsg;ErrorMsg::Info(Yii::t('yii','failure'));
8、测试结果。
{ "error": { "name": "Not Found", "message": "操作失败", "error_code": "20003" }}
完成。整个实现过程我采用语言包的形式,这样有利于后期多语言的切换。
常见问题
1、采用这种字符串模糊搜索很泛,无法达到具体错误类型返回对应具体代码的要求。如有更好的建议,欢迎大家提议。
$result = strstr($_errors,Yii::t('yii','Not exist'));
2、实现过程中没有考虑到今后多语言切换的问题,然后直接用传统的方式传提示语。比如:ErrorMsg::Info("操作失败");这样是无法实现多语言切换的。建议大家用语言包的方式传参。
相关资料
1、微博开放平台: http://open.weibo.com/wiki/Error_code
2、淘宝开放平台: http://open.taobao.com/doc2/apiDetail.ht...
3、PHP简单工厂模式、工厂方法模式和抽象工厂模式比较: http://www.phpddt.com/php/php-factory.ht...

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Alipay PHP...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.