<?php
$flag = true;
$data = array();
try {
if($flag == true){ //请求失败抛出异常
throw new Exception("Processing Request success", 1);
}else{ //请求成功也抛出异常
throw new Exception("Processing Request fail", 2);
}
} catch (\Exception $th) { //统一处理异常,返回信息
$message = $th->getMessage();
$code = $th->getCode();
echo json_encode(['message' => $message, 'code' => $code, 'data' => $data]);
die();
}
成功处理不抛异常
<?php
$flag = true;
$data = array();
try {
if($flag == true){
throw new Exception("Processing Request success", 1);
}
//以下为正常流程
} catch (\Exception $th) {
$message = $th->getMessage();
$code = $th->getCode();
echo json_encode(['message' => $message, 'code' => $code, 'data' => $data]);
}
echo json_encode(['message' => '请求成功', 'code' => 10000, 'data' => $data]);
die();
网友评论