Laravel 使用参数创建自定义异常并以 JSON 形式返回

Cat*_*tto 5 php laravel

如果变量为 null,我想抛出自定义异常并将其作为 JSON 返回。我尝试过这样的:

控制器

try {
    $check_api_key = $attendance_libraries->check_api_key($this->request);
    if ($check_api_key == null) {
        throw new NullException(false, 'API Key Not Found', null, 500);
    }
} catch (NullException $e) {
    return $e;
} catch (\Exception $e) {
    // do something else           
}
Run Code Online (Sandbox Code Playgroud)

自定义异常

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Response;

class NullException extends Exception
{
    public $is_success;
    public $message;
    public $code;
    public $data;

    public function __construct($is_success, $message, $code, $data = null, Exception $previous = NULL)
    {
        $this->is_success = $is_success;
        $this->message = $message;
        $this->code = $code;
        $this->data = $data;
    }

    public function render()
    {
        return response()->json([
            'success' => $this->is_success,
            'message' => $this->message,
            'data' => $this->data,
        ], $this->code);
    }
}

Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用邮递员测试它时,我得到的返回与我在 NullException 中编写的不一样。就变成这样了: 邮递员回复

Ram*_*ira 2

在您的情况下,您将返回异常作为响应,而不是抛出它。这就是为什么它会这样显示。

您可能只需抛出异常而不使用 try/catch:

$check_api_key = $attendance_libraries->check_api_key($this->request);

if ($check_api_key == null) {
    throw new NullException(false, 'API Key Not Found', null, 500);
}
Run Code Online (Sandbox Code Playgroud)

laravel 错误处理程序将捕获异常并渲染它。

编辑:或者正如 @miken32 指出的那样,您可以重新抛出异常来处理其他异常:

try {
 //...
} catch (NullException $e) {
  throw $e;
} catch (// other exceptions) {
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述