Learn the encapsulation of thinkphp5 commonly used api exception class ApiException
Encapsulate ApiException.php exception class
<?php
namespace app\common\lib\exception;
//引用异常类
use think\Exception;
//继承异常类
class ApiException extends Exception
{
//自定义http状态码
public $message = '';
public $httpCode = 400;
public $code = 0;
/*
* 渲染抛出异常的状态码和信息
*/
public function __construct($message = "", $httpCode = 0, $code = 0)
{
$this->message = $message;
$this->httpCode = $httpCode?:400;
$this->code = $code;
}
}
Call the exception class to throw an exception
Where an exception needs to be thrown, quote
//一定要优先引用后在调用
use app\common\lib\exception\ApiException;
//在方法中调用
$category_ay = [];
if (!$category_ay) {
throw new ApiException('暂无分类列表!');
}
//验证请求的app客户端是否合法
if (!in_array($header['apptype'], config('app.apptypes'))) {
throw new ApiException('客户端不合法!', 400);
}