thinkphp6 不可预知的异常处理 (api格式)

在应用目录下创建一个 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",
];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值