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

需求自定义一个异常返回状态码和错误提示 #119

Open
izhiqiang opened this issue Sep 5, 2024 · 0 comments
Open

需求自定义一个异常返回状态码和错误提示 #119

izhiqiang opened this issue Sep 5, 2024 · 0 comments

Comments

@izhiqiang
Copy link

起因:

'exception' => [

在配置文件中‘exception’ 相当于一个异常只能有一个状态码,当我需求是需要定义100个或则更多的时候 ,按照这个逻辑我就需要定义出100个或则更多的异常

期望:
定义一个异常,然后我们可以直接抛出这个异常,也可以直接继承这个异常,在异常中响应对应的状态码

我目前的做法是:
首先我定义一个异常类

<?php

namespace Jiannei\Response\Laravel\Support;

class ResponseException extends \RuntimeException
{
    public function __construct(string $message = '', $code = 201)
    {
        parent::__construct($message, $code);
    }
}

然后我异常处理Handler进行拦截

protected function prepareJsonResponse($request, $e)
    {
        if (is_subclass_of($e, ResponseException::class) || get_class($e) === ResponseException::class) {
            return Response::fail($e->getMessage(), $e->getCode(), $this->convertExceptionToArray($e));
        }
       -------------------------略过您的代码------------------------------------------------------
    }
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

No branches or pull requests

1 participant