Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重构 Handler,便于后期扩展 #1

Merged
merged 1 commit into from
May 20, 2022
Merged

重构 Handler,便于后期扩展 #1

merged 1 commit into from
May 20, 2022

Conversation

krissss
Copy link
Contributor

@krissss krissss commented May 20, 2022

当项目需要自定义情况比较多的时候,很可能需要扩展 Handler,此时可以继承 Handler 然后修改对应方法即可

@Tinywan
Copy link
Owner

Tinywan commented May 20, 2022

你这个是如何后期扩展?

@krissss
Copy link
Contributor Author

krissss commented May 20, 2022

项目中新建一个handler,然后继承你的这个,然后按需修改对应的方法。
比如我想response响应xml,只需要覆盖buildResponse方法;
再比如我想扩展其他Exception的响应,我只要覆盖solveExtraException;
再比如我要异常推送微信消息,我可以覆盖triggerNotifyEvent。

因为你原来的写法要扩展的话只能整个重写

@Tinywan
Copy link
Owner

Tinywan commented May 20, 2022

继承和使用的步骤是否可以提供一下,需要写文档

@Tinywan Tinywan merged commit a43a1e7 into Tinywan:main May 20, 2022
@krissss
Copy link
Contributor Author

krissss commented May 21, 2022

@Tinywan

<?php

namespace support;

use Illuminate\Validation\ValidationException;
use Throwable;
use Tinywan\ExceptionHandler\Handler;
use Webman\Http\Response;

class ErrorHandler extends Handler
{
    /**
     * @inheritDoc
     */
    protected function solveExtraException(Throwable $e): void
    {
        // 当前项目下的异常扩展
        if ($e instanceof ValidationException) {
            $this->exceptionInfo['errorMsg'] = $e->validator->errors()->first();
            $this->exceptionInfo['statusCode'] = 422;
            return;
        }

        parent::solveExtraException($e);
    }

    /**
     * @inheritDoc
     */
    protected function triggerNotifyEvent(Throwable $e): void
    {
        // 触发其他错误推送渠道

        parent::triggerNotifyEvent($e);
    }

    /**
     * @inheritDoc
     */
    protected function buildResponse(): Response
    {
        // 构造自己项目下的响应
        return json([
            'code' => $this->exceptionInfo['statusCode'], // 使用 statusCode 作为 code 返回
            'msg' => $this->exceptionInfo['errorMsg'],
            'data' => $this->responseData,
        ]);
    }
}

@Tinywan
Copy link
Owner

Tinywan commented May 21, 2022

谢谢!异常信息为了统一,我这里全部使用成员变量了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants