在Dart中,可以使用try-catch语句来捕获HTTP异常。以下是一个示例代码:
import 'dart:async';
import 'package:http/http.dart' as http;
void main() {
fetchUrl('https://example.com').then((response) {
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}).catchError((error) {
print('Error: $error');
});
}
Future fetchUrl(String url) async {
try {
final response = await http.get(url);
return response;
} catch (error) {
throw Exception('Failed to fetch URL: $url');
}
}
在上面的示例中,我们首先定义了一个fetchUrl
函数,该函数使用http
库中的get
方法来发送HTTP GET请求。在try块中,我们等待响应,并将其返回。如果在获取响应时出现错误,catch块将抛出一个自定义的异常。
在main
函数中,我们调用fetchUrl
函数并使用then
方法来处理成功的响应。如果在获取响应时出现错误,catchError
方法将捕获异常并打印错误消息。
请注意,此示例使用了http
库,因此您需要在pubspec.yaml
文件中添加以下依赖项:
dependencies:
http: ^0.13.4
确保在运行示例代码之前运行flutter pub get
命令来获取依赖项。