通过 HeadBucket 获取存储桶(Bucket)信息, 同时可以根据返回的 err 中的 HTTP Code 信息,判断桶是否存在。本文介绍如何获取桶元数据和判断桶是否存在。
tos:HeadBucket
权限。import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: "Provide your ak", accessKeySecret: "Provide your sk", securityToken: 'Provide your securityToken', region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error: Error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } const bucketName = 'harmonyos-sdk-test-bucket'; async function main() { try { // 判断桶是否存在 const res = await client.headBucket({ Bucket: bucketName }); console.log(`the region of ${bucketName} is`, res.Region); console.log(`the storageClass of ${bucketName} is`, res.StorageClass); } catch (error) { if (error instanceof TosServerError) { if (error.StatusCode === 404) { // 存储桶不存在 console.log('Bucket not found.'); return; } } handleError(error); } } main();
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk'; // 创建客户端 const client = new TosClient({ accessKeyId: "Provide your ak", accessKeySecret: "Provide your sk", securityToken: 'Provide your securityToken', region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,"Provide your region" 填写为 cn-beijing。 endpoint: "Provide your endpoint", // 填写域名地址 }); function handleError(error: Error) { if (error instanceof TosClientError) { console.log('Client Err Msg:', error.message); console.log('Client Err Stack:', error.stack); } else if (error instanceof TosServerError) { console.log('Request ID:', error.requestId); console.log('Response Status Code:', error.statusCode); console.log('Response Header:', error.headers); console.log('Response Err Code:', error.code); console.log('Response Err Msg:', error.message); } else { console.log('unexpected exception, message: ', error); } } const bucketName = 'harmonyos-sdk-test-bucket'; async function main() { try { // 判断桶是否存在 const res = await client.headBucket({ Bucket: bucketName }); console.log(`the region of ${bucketName} is`, res.Region); console.log(`the storageClass of ${bucketName} is`, res.StorageClass); console.log(`the azRedundancy of ${bucketName} is`, res.AzRedundancy) } catch (error) { handleError(error); } } main();
关于获取桶的元数据 API 文档,请参见 HeadBucket。