如何在Laravel 9中检查异常是否可报告?

wztqucjr  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(172)

我只有API laravel项目。如果我通过设置APP_DEBUG=false关闭.env文件中的调试模式,我的应用程序会抛出Server error错误,这些错误不应该显示给用户。
但是它返回json这样的响应:

{
    "message": "Server Error"
}

我想添加代码键到它的屁股好。我正在努力实现:

{
    "code": 500,
    "message": "Server Error"
}

到目前为止,我尝试了什么(Handlerregister方法):

$this->renderable(function (Throwable|Exception $e) {
        return response()->json([
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        ], $e->getCode());
    });

但这将返回异常消息,不应该显示给用户。我需要这样的smth:

$this->renderable(function (Throwable|Exception $e) {
        // ReportableException doesn't exist in laravel
        if($e instanceof ReportableException){
            return response()->json([
                'code' => 500,
                'message' => 'Server error'
            ], 500);
        }

        return response()->json([
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        ], $e->getCode());
    });
4nkexdtk

4nkexdtk1#

我发现有一个isHttpException方法可以用来判断异常是否可以报告给用户,这就是我的解决方案:

$this->renderable(function (Throwable $e) {
        if (!$this->isHttpException($e)){
            return response()->json([
                'code' => 500,
                'message' => "Internal server error"
            ], 500);
        }
        $code = $e->getCode() == 0 ? 500 : $e->getCode();

        return response()->json([
            'code' => $code,
            'message' => $e->getMessage()
        ], $code);
    });
a64a0gku

a64a0gku2#

您可以访问HttpResponseException,因此可以执行以下操作:

if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
    //Can use this directly for details
    $exception = $exception->getResponse();

    //Or handle the exception manually
    switch ($exception->getStatusCode()) {
        case 401:
            $response->code = 401;
            $response->message = 'Unauthorized';
            break;
        case 403:
            $response->code = 403;
            $response->message = 'Unauthorized';
            break;
        case 404:
            $response->code = 404;
            $response->message = 'Not Found';
            break;
        case 405:
            $response->code = 405;
            $response->message = 'Unauthorized';
            break;
        case 422:
            $response->code = 422;
            $response->message = '??';
            break;
        default:
            $response->code = 500;
            $response->message = '??';
            break;
    }
}

它看起来像这样:

if($e instanceof \Illuminate\Http\Exception\HttpResponseException){
     return response()->json([
         'code' => $e->getStatusCode(),
         'message' => 'Server error'
     ], $e->getStatusCode());
 }

希望这对你有用。

相关问题