记录一次使用webman异常处理类

金生水起

烦恼:之前总是在控制器每个方法中重复写try catch异常捕获感觉非常繁琐

// 之前写的 伪代码
class DemoController
{
    public function test(Request $request) {
        try{
            // 业务逻辑
        } catch (ValidationException $e) {
            // 验证器处理
        } catch (ApiException $e) {
            // 自定义异常处理
        } catch (\Exception $e) {
            // 系统异常处理
        }
    }
}

下面是修改之后的处理方式
第一步:

// 在support目录下创建Exception.php
namespace support;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
use App\api\Exception\ApiException;
use Respect\Validation\Exceptions\ValidationException;

class Exception extends \Webman\Exception\ExceptionHandler
{
    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof ValidationException) {
            // 验证器异常处理
            return json(['code'=>500, 'msg'=>$exception->getMessage()]);
        }

        if ($exception instanceof ApiException){
            // 自定义异常处理
            return json(['code'=>500, 'msg'=>$exception->getMessage()]);
        }

        if ($exception instanceof Throwable) {
            // 记录错误日志
            Log::error($exception->getMessage());
            return json(['code'=>500, 'msg'=>'系统异常']);
        }

        return parent::render($request, $exception); // TODO: Change the autogenerated stub
    }
}

第二步:

// 修改config/exception.php配置文件
return [
    // '' => support\exception\Handler::class,
    'api' => support\Exception::class,
];

现在在控制器写法伪代码

class DemoController
{
    public function test(Request $request) {
        // 直接抛出异常
        throw new ApiException('自定义异常');
    }
}
2571 2 3
2个评论

Tinywan

试试这个插件,会让你起飞:https://www.workerman.net/plugin/16

  • 金生水起 2022-11-13

    看了一下 很不错 感谢分享

  • ichynul 2022-11-14

    框架新版本businessExeption支持render方法,重写exceptionHandler都可以免了。
    直接抛businessExeption异常,或自己写个类继承businessExeption并重写render。

  • 史蒂芬 2023-01-19

    直接报错 Undefined array key "event_trigger" in /Users/wulinzhu/Documents/恒昌/项目/irm/vendor/tinywan/exception-handler/src/Handler.php:186 没读到配置文件,奇怪

powerbowen

我的

    //控制器
    public function getInfo(Request $request, AuthUserService $service): Response
    {
        try {
            return json(['code' => RespConst::RESP_SUCCESS_CODE, 'msg' => RespConst::RESP_SUCCESS_TEXT, 'data' => $service->info($request)]);
        } catch (WebmanException $e) {
            return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => []]);
        } catch (\Throwable $e) {
            return json(RespConst::RESP_SERVICE_ERROR_MAP);
        }
    }

    //manager
    public function savePassword(Request $request): void
    {
        try {
            ValidateFormTool::validator($request->post(), SavePasswordValidate::$rule, SavePasswordValidate::$message);

            /** @var UserModel $model */
            $model = $this->dao->findByAttribute(['uid' => $request->post('uid')])->getModel();
            $model || throw new WebmanException('用户不存在', RespConst::RESP_PARAMS_ERROR_CODE);

            $model->passwordRule($request->post('password')) || throw new WebmanException(AuthConst::PWD_RULE_ERR_MSG, RespConst::RESP_PARAMS_ERROR_CODE);
            $model->validatePassword($request->post('old_password')) || throw new WebmanException('`旧密码`错误', RespConst::RESP_PARAMS_ERROR_CODE);

            $this->dao->save(['password' => $request->post('password')]);
        } catch (WebmanException $e) {
            throw new WebmanException($e->getMessage(), intval($e->getCode()));
        } catch (\PDOException | \Exception | \Error $e) {
            throw new WebmanException(RespConst::RESP_SERVICE_ERROR_TEXT, RespConst::RESP_SERVICE_ERROR_CODE);
        } catch (\Throwable $e) {
            throw new WebmanException($e->getMessage(), RespConst::RESP_SERVICE_ERROR_CODE);
        }
    }

控制器转发
manager业务服务
service基础服务
dao数据处理
WebmanException 子定义,继承Exception
\PDOException | \Exception | \Error 其它特殊异常
Throwable 兜底

金生水起

200
积分
0
获赞数
0
粉丝数
2022-10-20 加入
🔝