How can I ignore a future exception of a http.post call? In the following code I want to send a message to the server, but I don't care about the response:
http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
body: json.encode({
'message': 'Event occurred',
}));
If the server at that URL is not running, this exception is thrown:
SocketException (SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 10.0.2.2, port = 41874)
I can prevent this exception from being thrown by doing await on the above call and wrapping that around a try-catch, but I don't want to block. The following code still results in the above exception:
http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
body: json.encode({
'message': 'Event occurred',
}))
.catchError((_) => http.Response('Logging message failed', 404));
ignore() and onError() have the same result.
I want ignore whatever exception http.post could throw without having to do an await, which blocks the code.
If you just print the error that you catched, it should't block the app.
http.post('http:/10.0.2.2/log-message',
body: json.encode({
'message': 'Event occurred',
}));
.catchError((_) => print('Logging message failed'));
There is no way to catch a SocketException without waiting for the result of the http.post operation, because it occurs later than the request is sent. Whether you use async/await with try/catch or .then and .catchError is your choice, but the preferred way is async/await:
Future<Response> myFunction async {
try {
return http.post(...);
} on SocketException {
// handle the exception here as you like
}
}
Related
Hello,
I am working with a login that works with websocket, when I send the correct parameters, the login connection is provided.It doesn't return me a statuscode 201 style message even if the connection is established.When I enter it wrong on purpose, it returns me this as an errorWebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'the url i entered#' was not upgraded to websocket the code is like this;
IOWebSocketChannel channel = new IOWebSocketChannel.connect("THE URL I ENTERED",headers: {"USER_ID":widget.user,"PASSWORD":widget.password},);
channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
channel.sink.close(status.goingAway);
print(status.goingAway);
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
print('socket closed: reason=[${channel.closeReason}], code:[${channel.closeCode}]');
debugPrint('ws error $error');
},
);
message i get in terminal
I/flutter ( 5598): socket closed: reason=[null], code:[null]
I/flutter ( 5598): ws error WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'THE URL I ENTERED' was not upgraded to websocket
I/flutter ( 5598): ws channel closed
My question is, I want it to return server respond code when I entered correctly or when I entered wrong. I did the same thing in different languages such as python, and it gives me feedback.
but here it comes only as null, I searched everywhere for the solution of this error for about 4 days, but I couldn't find it.waiting for you to help me
Best Regards
We are making a simple HTTP GET request to an API & noticing that when our HTTP requests error, the response body sometimes has more details then the error message. We are using the axios. We would like to access both the response and the error message from our code, but we are only seeing the error message and are unsure how to access the response. Here is our code:
Calling the API:
import { httpClient } from '../httpClient'; //AxiosInstance
type GetLocations = () => Promise<AxiosResponse<ILocation[]>>
const getLocations: GetLocations = async () => {
const url = `/Location`;
return httpClient.get(url);
}
const callAPI = async () => {
try {
const axiosResponse = await getLocations();
console.log(axiosResponse.data);
catch(error) {
// error.message has the error message, but we would like access to the http response body as well.
console.log(error)
}
}
Some Screenshots:
console.log(error):
The error object as JSON:
DevTools > Network > Our API Call > Response from same request that errored (has more info):
We would like to access this Incorrect syntax near ','. response from our catch block.
I'm working with the HttpService module from Nest.js to make the HTTP calls. I'm able to download an image from https://unsplash.com; when there is no network interruptions the code is working as expected.
This is the code I have for making the download call and start writing into the desired file
const urlDownload = 'https://unsplash.com/photos/xiie4XeSzTU/download?force=true';
let response = await this.httpService.get(urlDownload, {
responseType: 'stream'
}).toPromise();
response.data.pipe(writer);
And this is the code where I'm trying to handle the possible events of the writer and returning a response
let downloadFile = path.resolve(__dirname,'../../files/landscape.jpg');
let writer = fs.createWriteStream(downloadFile);
return new Promise((resolve, reject) => {
writer.on('finish', ()=>{
resolve('Image downloaded');
});
writer.on('error', ()=>{
reject('Image downloaded failed');
});
});
I'm deliberately turning off the wifi during the download to try the server response with Image downloaded failed (what I have in the writer error handler), but instead I'm getting an 500 statusCode, internal server error. When I go to the Nest console to whatch the error it appears
[Nest] 11220 - 2020-05-22 18:16:45 [ExceptionsHandler] getaddrinfo ENOTFOUND unsplash.com +439536ms
Error: getaddrinfo ENOTFOUND unsplash.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)
How can I solve this and catch correcty the network error from Nest to return a friendly message?
I could solve it. I let it here with the hope of helping somebody in the future.
It is not firing the error handler function because that handler is attached to the writter, and there is not writting error, it just stops writing because the cut of the connection but that is not an error.
I re-writed the response variable to stop being a promise and better I started treating it like an observer.
let response = this.httpService.get(urlDownload, {
responseType: 'stream',
});
And then it is the response in previus Promise format
return new Promise((resolve, reject) => {
writer.on('error', () => {
resolve('error due to, possibly, an unexisting file path');
})
response.subscribe({
next(response) { response.data.pipe(writer) },
error(err) {
console.error('More details: ' + err);
resolve('Error in the download :/')
},
complete() { resolve('Completed'); }
})
});
I'm not using the reject function of the promise but it is perfectly doable
I’m trying to POST using package:http/http.dart, but I’m getting a ClientException with no message:
Uriurl = Uri.https(baseURL, path);
return http.post(url, body: request.params, headers: _headers)
How do I find out what the error is? The path var contains a relative, valid path. If I replace it with some random string, I'm not getting the ClientException anymore.
I didn't find any way to receive the error description, but in my case (sometimes error "HttpException: Connection closed before full header was received" instead of blank error) the call was to an https address using Microsoft Internet Information Services as backend, in the SSL settings of the website in IIS i had mistakenly set "Client certificates: Accept" instead of "Client certificates: Ignore", setting "Ignore" solved the problem.
Just wrap it in a try-catch clause and you should see what error is being thrown.
try {
Uri url = Uri.https(baseURL, path);
return http.post(url, body: request.params, headers: _headers)
} catch (ex) {
print(ex); // This is your error
}
I am using the Flutter package esc_pos_printer 1.5.0 to print to a thermal receipt printer. It works fine if the printer is online but I get a socket timeout when it is not, even when I nest the code in a try / catch block.
Normally I expect the printer will be connected by Ethernet but it could also be WiFi.
The package author recommends using andrey-ushakov/ping_discover_network
but that package says in the README
Could be used to find printers (for example, on port 9100) and any
other devices and services in local network.
The device should be connected to a Wi-Fi network. wifi package allows
to get the local IP address / network subnet.
Here is the error:
ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception:
SocketException: OS Error: Connection timed out, errno = 110
Here is my code:
try {
Printer.connect('192.168.1.100', port: 9100).then( (printer) {
printer.println('welcome',
styles: PosStyles(
height: PosTextSize.size2,
width: PosTextSize.size2,
));
printer.cut();
printer.disconnect();
}
);
}
catch (e) {
print(e);
// do stuff
}
}
The problem is Printer.connect method returns a Future which means the work is done asynchronously.
Since the code execution is not on hold by await, the execution completes the method and returns to caller method without caring about the execution of code inside the block in .then().
What you can do is following:
you can use Future's catchError and catch the exception without waiting for the .then() block execution:
Printer.connect('192.168.1.100', port: 9100).then( (printer) {
printer.println('welcome',
styles: PosStyles(
height: PosTextSize.size2,
width: PosTextSize.size2,
));
printer.cut();
printer.disconnect();
}
).catchError((e) {
//handle the exception the way you want, like following
print('Caught error when processing: $e');
});
Keep the try catch as it is and just add await for the method call:
try{
final printer = await Printer.connect('192.168.1.100', port: 9100);
printer.println('welcome',
styles: PosStyles(
height: PosTextSize.size2,
width: PosTextSize.size2,
));
printer.cut();
printer.disconnect();
} catch (e) {
print(e);
// do stuff
}
Source for Future based error handling:https://dart.dev/guides/libraries/futures-error-handling
Let me know if you have any doubts.