Table of Contents
序言
实现思路
代码分析
常见问题
相关资料
Home Backend Development PHP Tutorial Restful api 错误提示返回实现思路

Restful api 错误提示返回实现思路

Jun 23, 2016 pm 01:10 PM

序言

不管是微博还是淘宝,他们都有自己的错误返回值格式规范,以及错误代码说明,这样不但手机端用起来方便,给人的感觉也清晰明了,高大上。遇到问题先找母本,大公司的规范就是我们参照的母本。为此,我仿照了淘宝的错误返回值格式,根据微博错误代码制定的标准自定了自己的错误代码,然后在Restful api 上进行测试。下面我将实现思路以及测试结果分享给大家。

实现思路

我利用抽象工厂模式去实现这样的一个错误返回值。选择这种模式是因为考虑到了这种模式可以提供一个创建一系列相关或相互依赖对象的接口,与我的需求很接近。

代码分析

1、按这个路径common\hint,我新建了个error文件夹存放我的错误提示程序文件。这文件夹中主要有这几个文件:

2、Hint.php入口文件。定义一个抽象类,里边只写一个方法。

interface  Hint {    function  Error($_errors,$code);}
Copy after login

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));        }    }}
Copy after login

4、createMsg.php 再创建一个createMsg抽象类。将对象的创建抽象成一个接口。

interface  createMsg {     function Msg();     }
Copy after login

5、用FactoryMsg 类去实现createMsg接口。返回实例化的Template。

class FactoryMsg implements createMsg{       function Msg() {        return  new  Template;    }}
Copy after login

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');              }}
Copy after login

7、调用方式。

use common\hint\error\ErrorMsg;ErrorMsg::Info(Yii::t('yii','failure'));
Copy after login

8、测试结果。

{    "error": {        "name": "Not Found",        "message": "操作失败",        "error_code": "20003"    }}
Copy after login

完成。整个实现过程我采用语言包的形式,这样有利于后期多语言的切换。

常见问题

1、采用这种字符串模糊搜索很泛,无法达到具体错误类型返回对应具体代码的要求。如有更好的建议,欢迎大家提议。

$result  = strstr($_errors,Yii::t('yii','Not exist'));
Copy after login

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...

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

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-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

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.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

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' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

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

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

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

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

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

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles