swoft-cloud / swoft

🚀 PHP Microservice Full Coroutine Framework
https://swoft.org
Apache License 2.0
5.58k stars 788 forks source link

ExceptionHandler 是否支持绑定多个异常到一个处理方法上 #265

Closed EdenChan closed 6 years ago

EdenChan commented 6 years ago

Details

目前似乎还没有看到有关 ExceptionHandler 的详细文档,如下在 Handler 注解中传入数组 {Exception::class, RuntimeException::class},期望可以在这个方法中同时处理这两个异常,这样可以不用写重复的处理逻辑,但是目前由于 Swoft\Bean\Annotation\Handler 的返回声明提示为 string,这样写会报错

不知是否有考虑支持绑定多个异常到一个处理方法上?还是认为一个异常对一个 handle 会更清晰?

    /**
     * @Handler({Exception::class, RuntimeException::class})
     *
     * @param Response   $response
     * @param \Throwable $throwable
     *
     * @return Response
     */
    public function handlerException(Response $response, \Throwable $throwable)
    {
        $file      = $throwable->getFile();
        $line      = $throwable->getLine();
        $code      = $throwable->getCode();
        $exception = $throwable->getMessage();
        $data = ['msg' => $exception, 'file' => $file, 'line' => $line, 'code' => $code];
        App::error(json_encode($data));
        return $response->json($data);
    }
yumufeng commented 6 years ago

RuntimeException继承于 Exception ,如果异常捕获中没有对RuntimeException独立的处理。捕捉了 Exception相当于RuntimeException的异常也会被捕捉。 1 楼主这不是个 伪需求麽?

EdenChan commented 6 years ago

@yumufeng 这是个示例,实际上代码中可能是几个没有继承关系的 Exception。