当前位置:网站首页>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 path
ExceptionHandler是我们自定义的异常,继承自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');
}
}
由于篇幅受限,就先说到这里.喜欢的可以点个关注,下期继续.
边栏推荐
- [CISCN2019 华东南赛区]Web11
- 2022-08-04T17:50:58.296+0800 ERROR Announcer-3 io.airlift.discovery.client.Announcer appears after successful startup of presto
- 将故事写成我们
- Getting Started with Kubernetes Networking
- Open-Falcon of operation and maintenance monitoring system
- Bosses, I noticed that a mysql CDC connector parameters scan. The incremental. Sna
- 用Unity发布APP到Hololens2无坑教程
- UE4 opens door via interaction (keyboard key)
- 35岁的软件测试工程师,月薪不足2W,辞职又怕找不到工作,该何去何从?
- 阿里本地生活单季营收106亿,大文娱营收72亿,菜鸟营收121亿
猜你喜欢
Use CH341A to program external Flash (W25Q16JV)
iMedicalLIS listener (2)
运维监控系统之Open-Falcon
Event parse tree Drain3 usage and explanation
public static
List asList(T... a) What is the prototype? Walter talked little knowledge | "remote passthrough" that something
UE4 通过互动(键盘按键)开门
MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现
Spark基础【介绍、入门WordCount案例】
How do newcomers get started and learn software testing?
随机推荐
Hard power or soft power, which is more important to testers?
[Paper Notes] MapReduce: Simplified Data Processing on Large Clusters
2022-08-04T17:50:58.296+0800 ERROR Announcer-3 io.airlift.discovery.client.Announcer appears after successful startup of presto
public static
List asList(T... a) What is the prototype? MySql index learning and use; (I think it is detailed enough)
UE4 第一人称角色模板 添加冲刺(加速)功能
Ice Scorpion V4.0 attack, security dog products can be fully detected
Growth-based checkerboard corner detection method
UE4 通过重叠事件开启门
[极客大挑战 2019]FinalSQL
ffmpeg 像素格式基础知识
DNS被劫持如何处理?
UE4 第一人称角色模板 添加蹲伏功能
如何解决复杂的分销分账问题?
Developing Hololens encountered The type or namespace name 'HandMeshVertex' could not be found..
What is the difference between SAP ERP and ORACLE ERP?
YYGH-13-客服中心
Dive into how it works together by simulating Vite
MRTK3开发Hololens应用-手势拖拽、旋转 、缩放物体实现
【背包九讲——01背包问题】