我有一段代码可以在 URI 有效时从 http URI 正确加载图像,但我无法弄清楚如何在 URI 无效时捕获 OpenAsync 抛出的异常(结果为 404)。
问题是当包含对 OpenAsync 的调用的 lambda 退出时,会抛出异常;在 try/catch 块中不会引发异常。
问题是:
捕获 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
}