在写api接口时,当从服务器返回的值不是我们期望的值时都属于异常。包括了非服务器异常(用户行为造成的),服务器异常。为了更直观的用json型式通知给用户,需要定义类进行接管
2.在app目录下创建目录lib\exception\
并创建两个类ExceptionHandler BaseException
<?php
namespace app\lib\exception;
use think\exception\Handle;
use think\facade\Env;
use think\Response;
use Throwable;
class ExceptionHandler extends Handle
{
private $msg ="服务器异常";
private $httpcode =500;
private $errorcode =19999;
public function render($request, Throwable $e): Response
{
// 是否处于调试状态下,当处于调试状态下就返回html格式的错误信息。否则返回json格式的错误提示
if(Env::get("APP_DEBUG")==1 && !$e->getCode())
{
// 其他错误交给系统处理
return parent::render($request, $e);
}
// 如果是服务器异常返回预先设置好的
if($e instanceof BaseException){
$this->msg = $e->getMessage()?:$this->msg;
$this->httpcode = $e->getStatusCode()?:$this->httpcode;
$this->errorcode = $e->getCode()?:$this->errorcode;
}
// 如果是服务器异常就返回服务器异常提示
$result_data = [
'message'=>$this->msg,
'data'=>[],
'errorcode'=>$this->errorcode
];
return json($result_data,$this->httpcode);
}
}
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace app\lib\exception;
use Exception;
/**
* HTTP异常
*/
class BaseException extends \RuntimeException
{
private $statusCode;
private $headers;
public function __construct(int $statusCode, string $message = '', $code = 0, Exception $previous = null, array $headers = [])
{
$this->statusCode = $statusCode;
$this->headers = $headers;
parent::__construct($message, $code, $previous);
}
public function getStatusCode()
{
return $this->statusCode;
}
public function getHeaders()
{
return $this->headers;
}
}
在控制器中需要抛出异常的地方写入
throw new BaseException(400,”异常描述”,19999);
即可
BaseException类是对HttpException类初始化参数位置作了调整,对HttpException 中的__construct(int $statusCode, string $message = ‘’, Exception $previous = null, array $headers = [], $code = 0)
改成
__construct(int $statusCode, string $message = ‘’, $code = 0, Exception $previous = null, array $headers = [])
当实例化时后面不需要的参数可以省略不填,代码更加简洁