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

一种 Laravel 异常上下文解决方案 | overtrue #109

Open
overtrue opened this issue Jan 21, 2021 · 6 comments
Open

一种 Laravel 异常上下文解决方案 | overtrue #109

overtrue opened this issue Jan 21, 2021 · 6 comments

Comments

@overtrue
Copy link
Owner

https://overtrue.me/laravel-exception-with-context/

异常时我们通常希望在用户测给一个友好的提示,但默认使用框架的异常处理方案是不 OK 的。
最近项目遇到一个情况,我们在遇到用户访问某个信息没有权限的时候,希望提示详细的原因,比如当访问一个团队资源时非成员访问的场景下会提示一个:您不是 [x...

@assert6
Copy link

assert6 commented Jul 7, 2021

博客的英文字体为啥大小写混乱啊😵

@overtrue
Copy link
Owner Author

overtrue commented Jul 7, 2021

@assert6 截图看看?

@wanghaida
Copy link

一开始我也自定义了一个 exception,但是感觉每次 throw 也有点麻烦,又因为前端信息展示没有那么复杂,我就直接修改了 Handler.php 的 render 方法:

public function render($request, Throwable $e)
{
    if ($request->is('api/*')) {
        $error = $this->convertExceptionToResponse($e);

        $response = [
            'success' => false,
            'code'    => $error->getStatusCode(),
            'data'    => null,
            'message' => 'Server Error',
        ];

        if (config('app.debug')) {
            $response = array_merge($response, [
                'message'   => empty($e->getMessage()) ? 'Server Error' : $e->getMessage(),
                'exception' => get_class($e),
                'file'      => $e->getFile(),
                'line'      => $e->getLine(),
                'trace'     => collect($e->getTrace())->map(function ($trace) {
                    return Arr:: except($trace, ['args']);
                })->all(),
            ]);
        }

        return response()->json($response, $error->getStatusCode());
    }

    return parent::render($request, $e);
}

@Lwzi
Copy link

Lwzi commented Jan 26, 2022

字里行间都是知识点啊。

@rainlam163
Copy link

6

@savvym
Copy link

savvym commented Jun 25, 2023

学到了

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

No branches or pull requests

6 participants