whether you can use throw new to throw a http exception when developing api;
then it feels very simple. For example, if the user does not log in, the exception will be thrown directly, and the subsequent code will not be executed.
customize a http exception to take over the exception handling of the framework! The frame is tp5
or is it better to use the traditional return array to call the next level?
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/1/14/014
* Time: 2:56
*/
namespace app\tool\exception;
use app\tool\Tool;
use Exception;
use think\exception\Handle;
use think\Request;
use think\Log;
class ExceptionHandler extends Handle
{
private $status; //HTTP
private $msg; //
private $data; //
private $code;
public function render(Exception $e)
{
//
if ($e instanceof Base) {
$this->status = $e->status; //
$this->msg = $e->msg; //
$this->data = $e->data; //
$this->code = $e->code; //
} else {
if (\think\facade\Config::get("app_debug")) {
//
return parent::render($e);
} else {
//
$this->status = 500;
$this->msg = "";
$this->data = "";
}
//
$this->recordErrorLog($e);
}
//JSON
$response["status"] = $this->status;
$response["msg"] = $this->msg;
$response["data"] = $this->data;
return json($response, $this->code);
}
//
private function recordErrorLog(Exception $e)
{
Log::init([
"type" => "File",
//
"path" => LOG_PATH,
//
"level" => ["error"],
]);
Log::record($e->getMessage(), "error");
}
}
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/1/14/014
* Time: 2:47
*/
namespace app\tool\exception;
use think\Exception;
class Base extends Exception
{
public $status = 0; //HTTP
public $msg = ""; //
public $data = []; //
public $code = 200;
/**
* @desc
* BaseException constructor.
* @param array $params
* @throws Exception
*/
public function __construct($params = [])
{
//
if(!is_array($params)){
throw new Exception("");
}
//code
//
if(array_key_exists("status",$params)){
$this->status = $params["status"];
}
// msg
//
if(array_key_exists("msg",$params)){
$this->msg = $params["msg"];
}
// error_code
//
if(array_key_exists("data",$params)){
$this->data = $params["data"];
}
if(array_key_exists("code",$params)){
$this->code = $params["code"];
}
}
}
namespace app\tool\exception;
class Http extends Base
{
public $status = 0;
public $data = [];
public $msg = "!";
public $code = 200;
}
public static function getUid()
{
$token = Request::header("token");
if (null === $token) {
throw new Http(["status" => "-2", "msg" => "!"]);
}
$result = Cache::get($token);
if (false === $result) {
throw new Http(["status" => "-1", "msg" => ",!"]);
}
return $result["id"];
}