BusinessException类:
<?php
namespace app\common\exception;
use app\common\utils\ResponseUtils;
use think\Exception;
class BusinessException extends Exception
{
/**
* 异常数据信息
* @var object|string
*/
private $errData;
/**
* BusinessException constructor.
* @param array $businessStatus 异常状态及提示
* @param object $data 异常数据信息
*/
public function __construct($businessStatus) {
$this->errData =$businessStatus[1];
parent::__construct($businessStatus[1], $businessStatus[0]);
}
/**
* 获取异常数据
* @return object|string
*/
public function getError() {
return ResponseUtils::retError($this->errData);
}
}
BusinessExceptionHandler类:
<?php
namespace app\common\exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
class BusinessExceptionHandler extends Handle {
public function render($request, Throwable $e): Response
{
// 参数验证错误
if ($e instanceof BusinessException) {
return json($e->getError(), 200);
}
// 其他错误交给系统处理
return parent::render($request, $e);
}
}
错误枚举类:
<?php
namespace app\common\exception;
class BusinessExceptionEnum
{
const SUCCESS = [200, "成功"];
const PASSWORD_WRONG=[400,"密码错误"];
const USERNAME_WRONG=[401,'用户名不存在'];
const USERNAME_ALREADY=[402,'用户名已存在'];
const SIGN_WRONG=[403,'签名错误'];
const USERNAME_PASSWORD_WRONG=[404,'用户名或密码错误'];
const JWT_WRONG=[500,'token错误'];
const FILE_EMPTY=[501,'文件为空'];
const FILE_WRONG=[502,'文件格式不被支持'];
const SYSTEM_ERROR=[600,'系统错误'];
}
抛出错误:
throw new BusinessException(BusinessExceptionEnum::SYSTEM_ERROR);
这样就可以抛出指定格式的JSON串给前端
评论