Table of Contents
Restful api error prompt return value implementation idea in PHP, restful api
Articles you may be interested in:
Home Backend Development PHP Tutorial Restful api error prompt return value implementation ideas in PHP, restfulapi_PHP tutorial

Restful api error prompt return value implementation ideas in PHP, restfulapi_PHP tutorial

Jul 12, 2016 am 08:54 AM
api restful return

Restful api error prompt return value implementation idea in PHP, restful api

RESTful architecture is a popular Internet software architecture. It has a clear structure, conforms to standards, is easy to understand, and is easy to expand.

REST is the abbreviation of Representational State Transfer, which translates as "presentation layer state transformation". The presentation layer is actually a resource, so it can be understood as "resource status transformation".

Any entity on the web application can be regarded as a resource, pointed to by a URI (Uniform Resource Locator).

Preface

Whether it is Weibo or Taobao, they have their own error return value format specifications and error code descriptions, which are not only convenient to use on mobile phones, but also give people a clear and high-end feeling. When we encounter problems, we should first go to the parent company. The norms of large companies are the mother parent for us to refer to. To this end, I imitated Taobao's error return value format, customized my own error code based on the standards set by Weibo error codes, and then tested it on the Restful api. Below I will share with you the implementation ideas and test results.

Implementation ideas

I use the abstract factory pattern to implement such an error return value. I chose this pattern because it provides an interface for creating a series of related or interdependent objects, which is very close to my needs.

Code Analysis

1. According to this path commonhint, I created a new error folder to store my error prompt program files. This folder mainly contains these files:

2. Hint.php entry file. Define an abstract class and write only one method in it.

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

3. Template.php implements the Hint interface. The format of the error return value is defined here.

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 Create another createMsg abstract class. Abstract object creation into an interface.

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

5. Use FactoryMsg class to implement the createMsg interface. Returns the instantiated Template.

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

6. ErrorMsg.php passes parameters to the Error method in Template.

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

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

8. Test results.

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

Done. The entire implementation process is in the form of language packs, which will facilitate later multi-language switching.

FAQ

1. Using this kind of string fuzzy search is very general and cannot meet the requirement of returning specific codes corresponding to specific error types. If you have any better suggestions, you are welcome to make them.

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

2. During the implementation process, the issue of multi-language switching in the future was not considered, and prompts were directly transmitted in the traditional way. For example: ErrorMsg::Info("Operation failed"); In this way, multi-language switching cannot be achieved. It is recommended that you use language packs to pass parameters.

Articles you may be interested in:

  • PHP implements automatic recognition of the return content type of Restful API

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1119966.htmlTechArticle Restful api error prompt return value implementation ideas in PHP, restfulapi RESTful architecture is a popular Internet software architecture. The structure is clear, standard-compliant, easy to understand, and easy to expand. ...
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)

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

What results does MySQL return after inserting data? What results does MySQL return after inserting data? Mar 01, 2024 am 10:27 AM

MySQL is a widely used relational database management system for storing and managing data. When we want to insert new data into a database table, we usually use the INSERT statement. In MySQL, when the INSERT statement is executed to successfully insert data, a result will be returned, which is the result of the insertion operation. In this article, we will discuss in detail the results returned by MySQL after inserting data and provide some specific code examples. 1. The result returned after inserting data is in MySQL. When successfully executed

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

See all articles