当前位置:网站首页>Some conventional routines of program development (1)
Some conventional routines of program development (1)
2022-08-05 03:59:00 【develop that】
Into software development for a long time,期间做过Android,玩过opencv,做过小程序,写过TP5的接口.Now I will share with you some routine routines in software development.The server side will be TP5框架为例,The client takes WeChat applet as an example.
服务器方面
(以TP5为例)
The main job of server developers is to write interfaces.Including processing the data passed by the client,As well as passing the information from the database to the client.个人理解,before project development,The first thing to do is to design the database,Understand the relationship between tables,This is especially important for server developers,Because the content in the interface is ultimately the relationship between the table and the table.
Whether it is a background server or a foreground client,The first step in project development is to write the base class,Build the basic framework functions.Maybe the company has a framework,But you can't deny that this step can really save a lot of time for later work.接下来,从TP5development angle,Talk about some of my own routines in development.
大家都知道,When the server is developed and tested offline,Exceptions are also encountered online,在我们公司,It is parsed by the clientjsonString to report to the client.一般,Throws all expected exceptions,Exception handling on the client side.Only if the server executes the code correctly as planned,In order to make the correct response on the client side.The method used here is to extract the exception base class and define the global exception.
Extract the exception base class
First, let's take a look at how the data displayed on the client side looks like.
When the server encounters an exception,响应的数据. 
Data returned to the client when the server responds correctly 
这里先来说说,How to handle exceptions.When an exception can be seenjson字符串中有statue msg errorCode 以及 url,我们在自己写的BaseException(继承TP5中的Exception)Define these fields.will be customized globallyHandLermet in.Let's take a look at the code in detail
The method to call when the response is correct,We can extract it into the base class,Of course you can also define publicphp文件common.php
function show($status, $message,$data=array()) {
$reuslt = array(
'status' => $status,
'msg' => $message,
'data' => $data,
);
exit(json_encode($reuslt));
}class BaseException extends Exception {
//以下定义的变量 在全局异常处理类中会用到
public $status=0;//服务器状态码 0代表异常,1代表正确响应
public $code =400;//Http状态码 404 .402
public $msg="param error";//错误具体信息
public $errorCode=10000;//自定义错误码
/** * 构造函数,接收一个关联数组 * @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值 */
public function __construct($params=[]) {
if(!is_array($params)){
return;
}
if(array_key_exists('code',$params)){
$this->code = $params['code'];//将传递过来的值赋值给成员变量(java里的说法)
}
if(array_key_exists('msg',$params)){
$this->msg = $params['msg'];
}
if(array_key_exists('errorCode',$params)){
$this->errorCode = $params['errorCode'];
}
if(array_key_exists('status',$params)){
$this->errorCode = $params['status'];
}
}
}需要注意的是BaseException的构造方法,It's used quite cleverly here,通过这种方式,We can be very directBaseExceptionCustomize the parameters passed to the client in ,It is convenient for the front-end developers to make the correct response.
示例
throw new BaseException([
"msg"=>"测试异常",
"statue"=>1,
"errorCode"=>10011]);
定义全局异常处理
Of course you want to achieve the above effect,Just defining the base class exception is not enough.Additional custom global exception handling is required.在TP5in the frameconfig.php文件中有一个exception_handle变量,Used to specify what to call when the server is abnormalhandler处理方法.We can set its path to the inheritance we wrote ourselvesHandlerclass to implement global exceptions.
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => 'app\lib\exception\ExceptionHandler',//Custom exception pathExceptionHandler是我们自定义的异常,继承自TP5框架的Handler,而在Hanler中有一个render方法,In which can accept thrown from the backgroundException,Thereby making a response to the client.We can redefine this method in subclasses,输出json字符串,to achieve the effect in the example above.下面来看看具体代码.
class ExceptionHandler extends Handle {
//The variables defined below are the responses to the client
public $code;
public $msg;
public $errorCode;
public $status;
public function render(Exception $e) {
//传递过来的Exceptionis captured by the program,It can be thrown by ourselves
if ($e instanceof BaseException) {
//Make a judgment if it is our custom exception,Then output custom exception information
$this->code = $e->code;//将BaseException中的值赋值给成员变量,最后进行输出
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
$this->status = $e->status;
} else {
$switch = true;
if (config('app_debug')) {
//判断是否为调试模式,
//返回默认界面
return parent::render($e);
} else {
//返回json数据
$this->code = 500;
$this->msg = "服务器内部错误";
$this->errorCode = 999;
$this->status = 0;
$this->recordLog($e);
}
}
$request = Request::instance();
$result = [
"status" => $this->status,
"msg" => $this->msg,
"errorCode" => $this->errorCode,
"url" => $request->url()
];
return json($result, $this->code);
}
//记录日志方法
private function recordLog(Exception $e) {
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error'],
]);
Log::record($e->getMessage(), 'error');
}
}由于篇幅受限,就先说到这里.喜欢的可以点个关注,下期继续.
边栏推荐
- Package zip is not available, but is referred to by another package.
- 【8.3】代码源 - 【喵 ~ 喵 ~ 喵~】【树】【与】
- YYGH-13-Customer Service Center
- 调用阿里云oss和sms服务
- Leading the highland of digital medicine, Zhongshan Hospital explores to create a "new paradigm" for future hospitals
- [Paper Notes] MapReduce: Simplified Data Processing on Large Clusters
- Use Unity to publish APP to Hololens2 without pit tutorial
- Solana NFT开发指南
- Ali's local life's single-quarter revenue is 10.6 billion, Da Wenyu's revenue is 7.2 billion, and Cainiao's revenue is 12.1 billion
- Web3.0 Dapps - the road to the future financial world
猜你喜欢

Use Unity to publish APP to Hololens2 without pit tutorial

bytebuffer 内部结构

public static
List asList(T... a) What is the prototype? 
Web3.0 Dapps - the road to the future financial world

如何解决复杂的分销分账问题?

Static method to get configuration file data

将故事写成我们

UE4 第一人称角色模板 添加蹲伏功能

token、jwt、oauth2、session解析

从企业的视角来看,数据中台到底意味着什么?
随机推荐
DEJA_VU3D - Cesium功能集 之 057-百度地图纠偏
队列题目:最近的请求次数
markdown如何换行——md文件
Fifteen. Actual combat - MySQL database building table character set and collation
905. Interval selection
cross domain solution
Mathematics - Properties of Summation Symbols
日志导致线程Block的这些坑,你不得不防
DEJA_VU3D - Cesium功能集 之 058-高德地图纠偏
Walter talked little knowledge | "remote passthrough" that something
Common open source databases under Linux, how many do you know?
冰蝎V4.0攻击来袭,安全狗产品可全面检测
Increasing leetcode - a daily topic 1403. The order of the boy sequence (greed)
Web3.0 Dapps——通往未来金融世界的道路
35岁的软件测试工程师,月薪不足2W,辞职又怕找不到工作,该何去何从?
21 Days Learning Challenge (2) Use of Graphical Device Trees
Redis1:Redis介绍、Redis基本特性、关系型数据库、非关系型数据库、数据库发展阶段
DEJA_VU3D - Cesium功能集 之 059-腾讯地图纠偏
Package zip is not available, but is referred to by another package.
事件解析树Drain3使用方法和解释