繁体   English   中英

如何在Rest API中实现错误?

[英]How implement error in Rest API?

我想知道哪种是在RestAPI中实现错误的方法,实际上,如果类中的方法生成异常,我将返回此错误...

if(mysqli_connect_errno()) {
     throw new Exception("Can't connect to db.");
}

...但这是一个不好的做法,因为API应该返回json。

所以我的想法是创建一个名为Errors的类,在每个类中,当引发错误时,我只需调用相对错误号即可显示json错误。

有人有其他想法吗?

也许像这样:

<?php

try {
    // Do your stuff
    if(mysqli_connect_errno()) {
        throw new Exception("Can't connect to db.");
    }
} catch (Exception $e) {
    echo json_encode(array("success" => false, "message" => $e->getMessage()));
    return;
}

我认为您的做法正确。 您在这里要处理几个问题。 第一个是错误处理,第二个是错误格式化。

错误处理可以通过多种方式完成,引发异常是其中之一。 为了找出什么时候发生了不好的事情,您需要将异常包装在try / catch块中:

try {
    //logic
    if(mysqli_connect_errno()) {
        throw new Exception("Can't connect to db.");
    }
    //more logic
} catch (Exception $e) {
    //handle the error here
}

如果您遵循此路线,建议您对例外情况进行更详细的说明,以便更好地在API中构建响应。 例如,关闭数据库与无法找到资源并不相同,例如:

try {
    //logic
    if(mysqli_connect_errno()) {
        throw new DBException("Can't connect to db.");
    }

    if(is_null($entity)) {
        throw new ResourceNotFoundException("Entity could not be found");
    }
    //more logic
} catch (DBException $e) {
    //handle DB error here
} catch (ResourceNotFoundException $e) {
    //handle resource not found error here
}

现在,对于格式化部分 ,REST API中的常规响应是JSON响应。 一种解决方法是创建一个特定的类,其唯一职责是将您的响应转换为有效的JSON:

...
} catch (DBException $e) {
    return $this->JSONResponse->format("Sorry we could not complete your request", 500);
} catch (ResourceNotFoundException $e) {
    return $this->JSONResponse->format("The resource you were looking for could not be found", 404);
}

如您所见,不同的错误具有不同的状态代码。 该类的实现很简单:

class JSONResponse {
    public function format($message, $statusCode) {
         return json_encode(['message' => $message, 'code' => $statusCode]);
    }
}

但是,这不会更改响应的状态码,这对于良好的REST API设计至关重要。 您需要使用此功能设置适当的状态代码。

您可以在Symfony HTTPFoundation组件中找到该类的更健壮和灵活的实现,该组件是从正常Response类扩展的。

我认为@Gwendal答案很好,但仅返回json响应还不够,还必须返回正确的http代码:

<?php

try {
    // Do your stuff        
} catch (Exception $e) {
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    echo json_encode(array("success" => false, "message" => $e->getMessage()));
    return;
}

我的RESTful API始终返回以下结构的JSON:

[
    'resource' : [],

    'code'     : [
        'id'   : int,
        'msg'  : string
    ],

    'meta'     : [],

    'log'      : []
]

如果我返回数据,则数据始终在resource并且code['id']始终为0(表示“确定”)。 当发生错误时,我返回一个空resource和一些错误code 我还通过meta提供了一些额外的信息,并且可以通过log记录一些操作,这对调试很有帮助。

这也可能会帮助您解决将来的问题,例如,如果您想将答案分成多个页面,以便客户端应通过GET /path/to/resource/page/:page请求数据,或希望通知客户端某个请求路径不推荐使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM