今天凌晨写了一片关于laravel9.x 的自定义异常捕获返回json
今天看了一下文档 , 写了一下 , 发现TP自定义异常比Laravel稍微复杂一些
这里需要创建两个类才能实现这个自定义的异常
异常类
首先创建一个异常类 , 我实在 app \ common \ exception 这个文件夹创建的
注意 , 异常类是继承Exception
<?php
namespace app\common\exception;
use think\Exception;
class BusinessException extends Exception
{
public $msg = '异常';
public $errorCode = 999; // 自定义请求code
public $code = 200;
public function __construct($info ,$code)
{
$this->msg = $info;
$this->errorCode = $code;
}
}
异常处理类
创建一个异常类 , 我实在 app \ common \ exception 这个文件夹创建的
注意 , 异常类是继承Handle
<?php
namespace app\common\exception;
use think\exception\Handle;
use think\Response;
use Throwable;
class BusinessExceptionHandler extends Handle
{
public $msg;
public $errorCode;
public function render($request, Throwable $e): Response
{
if ($e instanceof BusinessException) {
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
}else{
return parent::render($request ,$e);
}
return json(["message" => $this->msg, "code" => $this->errorCode]);
}
}
容器
在app\provider.php这个文件中 , 复制一行异常处理代码 , 放入我们新建的异常处理类
<?php
use app\ExceptionHandle;
use app\Request;
// 容器Provider定义文件
return [
'think\Request' => Request::class,
'think\exception\Handle' => ExceptionHandle::class,
'think\exception\Handle' => \app\common\exception\BusinessExceptionHandler::class,
];
日志记录
一般这种我们手动抛出的业务是无需进行日志记录的
所以在应用异常处理类中添加我们写的异常类
<?php
namespace app;
use app\common\exception\BusinessException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
/**
* 应用异常处理类
*/
class ExceptionHandle extends Handle
{
/**
* 不需要记录信息(日志)的异常类列表
* @var array
*/
protected $ignoreReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
DataNotFoundException::class,
ValidateException::class,
BusinessException::class,
];
/**
* 记录异常信息(包括日志或者其它方式记录)
*
* @access public
* @param Throwable $exception
* @return void
*/
public function report(Throwable $exception): void
{
// 使用内置的方式记录异常日志
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @access public
* @param \think\Request $request
* @param Throwable $e
* @return Response
*/
public function render($request, Throwable $e): Response
{
// 添加自定义异常处理机制
// 其他错误交给系统处理
return parent::render($request, $e);
}
}
控制器调用
public function index()
{
throw new BusinessException("id不能为空",0);
}
看下是不是我在异常处理类中定义的json格式吧
下篇文章是swoft2.x框架的自定义异常