描述:开发需要全部json数据抛出,但是再tp6验证器的时候,异常抛出,导致这个环节无法抛出json数据!
try {
validate(\app\validate\Phone::class)->scene('Sms')->check($data);//验证器
} catch (ValidateException $e) {
dump($e->getError());//抛出异常
}
在:$e->getError(); 这个地方不需要异常,需要json返回
开始:
1:修改app/common.php公共方法文件中新建方法returnCode()
function returnMsg($status,$message,$data=array()){
$result =array(
'code'=>$status,
'msg'=>$message,
'data'=>$data,
);
return json($result);
}
2:修改app/provide.php文件为:
<?php
use app\ExceptionHandle;
return [
'think\exception\Handle' => '\\app\\common\\HttpException',
];
3:app下新建common模块,在common模块下新建 HttpException.php文件
<?php
namespace app\common;
use think\exception\Handle;
use think\Response;
use Throwable;
class HttpException extends Handle
{
public $httpCode = 500;
public function render($request, Throwable $e): Response
{
if (method_exists($e,"getStatusCode")){
$httpCode = $e->getStatusCode();
}else{
$httpCode = $this->httpCode;
}
return returnMsg($httpCode, $e->getMessage(),[]);
}
}
然后异常抛出试试