异常处理
更新时间:2026-09-23
BOS PHP SDK 的异常分为如下几种,均位于命名空间 BaiduBce\Exception 下(InvalidArgumentException 为 PHP 系统内置异常):
| 异常类 | 说明 |
|---|---|
BceBaseException |
异常基类,所有 BCE 异常的父类,可用于统一捕获。 |
BceClientException |
客户端异常,请求发送前或数据传输过程中在客户端发生的异常。 |
BceServiceException |
服务端异常,BOS 服务端返回错误时抛出,携带 requestId、错误码、HTTP 状态码等信息。 |
InvalidArgumentException |
参数错误,调用接口时传入非法参数(PHP 内置异常)。 |
用户可以使用 try/catch 捕获某次调用产生的异常。BCE 的客户端异常与服务端异常都继承自 BceBaseException,捕获该基类即可统一覆盖;而参数错误抛出的是 PHP 内置的全局 \InvalidArgumentException(并不属于 BaiduBce\Exception 命名空间,也不继承 BceBaseException),如需单独处理,应在外层另用一个 catch 捕获:
PHP
1try {
2 $client->deleteObject($bucketName, $objectKey);
3} catch (\BaiduBce\Exception\BceBaseException $e) {
4 print $e->getMessage();
5 if (strcmp(get_class($e), "BaiduBce\Exception\BceClientException") == 0) {
6 print "Catch a client exception";
7 }
8 if (strcmp(get_class($e), "BaiduBce\Exception\BceServiceException") == 0) {
9 print "Catch a service exception";
10 }
11 if (strcmp(get_class($e), "BaiduBce\Exception\BceBaseException") == 0) {
12 print "Catch a base exception";
13 }
14} catch (\InvalidArgumentException $e) {
15 print "Catch an invalid argument exception: " . $e->getMessage();
16}
客户端异常
客户端异常(BceClientException)表示客户端尝试向 BOS 发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用,或上传文件时发生 IO 异常,都会抛出 BceClientException。
服务端异常
当 BOS 服务端出现异常时,会返回相应的错误信息以便定位问题,SDK 将其封装为 BceServiceException 抛出。常见服务端异常可参见 BOS 错误信息格式。
BceServiceException 在 getMessage() 之外,还提供以下方法便于精确定位问题:
| 方法 | 返回值类型 | 说明 |
|---|---|---|
getRequestId() |
string | 本次请求的 requestId,排查问题时可提供给技术支持。 |
getErrorCode() |
string | 服务端返回的错误码,如 NoSuchKey、AccessDenied 等。 |
getStatusCode() |
int | 本次请求的 HTTP 状态码,如 404、403 等。 |
示例:
PHP
1try {
2 $client->getObjectMetadata($bucketName, $objectKey);
3} catch (\BaiduBce\Exception\BceServiceException $e) {
4 printf(
5 "service exception: message=%s, requestId=%s, code=%s, status=%d\n",
6 $e->getMessage(),
7 $e->getRequestId(),
8 $e->getErrorCode(),
9 $e->getStatusCode()
10 );
11}
评价此篇文章
