在应用目录下创建一个 exception文件 并且创建一个ApiException.php文件
<?php
namespace app\api\exception;
use think\exception\Handle;
use think\Response;
use Throwable;
class ApiException extends Handle{
public $httpStatus = 500;
/**
* 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
{
if ($e instanceof \think\Exception) {
return show($e->getCode(),$e->getMessage());
}
if ($e instanceof \think\exception\HttpResponseException) {
return parent::render($request, $e);
}
if(method_exists($e,'getStatusCode')){
$httpStatus = $e->getStatusCode();
}else{
$httpStatus = $this->httpStatus;
}
// 添加自定义异常处理机制
return show(config('status.error'),$e->getMessage(), [], $httpStatus);
}
}
app目录下的provider.php复制一下应用目录下
容器里面的异常处理改成复制的路径
<?php
use app\ExceptionHandle;
use app\Request;
// 容器Provider定义文件
return [
'think\exception\Handle' => "app\\api\\exception\\Http",
];