如果变量为null,我想抛出一个自定义异常,并将其作为JSON返回.

Controller

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           
}

Custom Exception

<?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);
    }
}

But when I am trying to test it using postman, the return I got is not the same as I wrote in NullException. It becomes like this: Postman response

推荐答案

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

您可能只需在不使用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);
}

laravel error handler人将抓住例外&;渲染它.

EDIT:或@miken32指出,您可以重新抛出异常以处理其他异常:

try {
 //...
} catch (NullException $e) {
  throw $e;
} catch (// other exceptions) {
}

enter image description here

Php相关问答推荐

输入手写CSV时在PHP中进行日期判断

尽管包含目标日期,但日期范围比较仍有意外输出

使用WooCommerce本机产品短码时不考虑价格筛选(_SHORT CODE)

一列必须指定多个变量的Laravel查询

PHP:PHP手册-Manual

如何将隐式乘法添加到PHPPEG基本计算器语法中?

在冲突和几何上插入的Postgres参数化查询在PHP中不起作用

如何使用php一次更新两个数据库中的MySQL表

将SVG包含在另一个php生成的SVG中

PHP -将字符串拆分为两个相等的部分,但第二个字符串中的单词更多

在WooCommerce管理中为订单项目添加自定义字段价格值

为什么从一个页面到另一个页面都找不到 JQuery,因为它们使用相同的 twig 模板?

使用 Composer 找不到 Google APIClient 类

由于 PHP 版本不受支持,如何终止 PHP 脚本?

为什么foreach循环会输出每个结果?

保留 .htaccess 中的符号登录 URL

在 Laravel、Vuejs 和 Inertia 中配置 TypeScript 的问题

如何在不解压缩/重新压缩的情况下连接(连接)两个缩小的值

php-http/discovery 插件 1.15.1 是否仍在使用自己的模块 destruct Contao 4.13 中的composer 安装?

路由未定义的 laravel 导出