gpt4 book ai didi

c++ - URI 错误时如何处理 StorageFile::OpenAsync 的异常

转载 作者:行者123 更新时间:2023-11-30 02:55:41 24 4
gpt4 key购买 nike

我有一段代码可以在 URI 有效时从 http URI 正确加载图像,但我不知道如何捕获 OpenAsync 在 URI 无效时抛出的异常(结果为 404)。

问题是当包含调用 OpenAsync 的 lambda 退出时,抛出异常;在 try/catch block 中不会抛出异常。

问题是:

捕获 StorageFile::OpenAsync 抛出的异常的正确方法是什么?

auto bm = ref new BitmapImage();
try {
Uri^ uri = ref new Uri("http://invaliduri.tumblr.com/avatar/128");

auto task = Concurrency::create_task(CreateStreamedFileFromUriAsync("temp-web-file.png", uri, nullptr));

task.then([] (StorageFile^ file) {
try {
return file->OpenAsync(FileAccessMode::Read);
} catch (...) {
// this does not catch the exception because the exception
// occurs after this lambda is exitted
}
}).then([bm](IRandomAccessStream^ inputStream) {
try {
return bm->SetSourceAsync(inputStream);
} catch (...) {
// this does not catch the exception because the exception
// occurs before this lambda is entered
}
});
} catch (...) {
// and obviously this would not catch the exception
}

最佳答案

3 年后我有这个问题。我引用了 this article .然后,我的方案解决如下,

#include<ppltasks.h>
...
auto file = ref new Windows::Foundation::Uri::Uri("ms-appx:///SomeFile.txt");
concurrency::create_task(Windows::Storage::StorageFile::GetFileFromApplicationUriAsync(data))
.then([](Windows::Storage::StorageFile^ f) {
return Windows::Storage::FileIO::ReadTextAsync(f);
})
.then([this](String^ s) {
this->someFileContent = s;
})
.then([](concurrency::task<void> t) {
try {
t.get();
} catch(Platform::COMException^ e) {
OutputDebugString(e->Message->Data());
}
});

此异步任务链可能会在 GetFileFromApplicationUriAsyncReadTextAsync 中失败并抛出异常。关键是抛出时唯一匹配的 then(...) 原型(prototype)是最后一个。在进入 try block 时,task::get 会代表您重新抛出并发类捕获的异常。

关于c++ - URI 错误时如何处理 StorageFile::OpenAsync 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com