curl-library
Re: How to capture Error message from the Server
Date: Tue, 17 May 2016 19:08:04 -0400
On 5/17/2016 5:24 PM, Colin Ngam wrote:
> Say, I need to read a file and it has “This is a test.” in it.
>
> I issue a GET for an object in the cloud. My callback is called with “This is a test.” in the buffer. I saved it into a local file. All is fine.
>
> Now, if someone deleted the object. I did not know. I issue a GET. My callback gets:
>
>
> <?xml version="1.0" encoding="UTF-8"?>
> <Error><Code>NoSuchKey</Code><Message>The specified key does not
> exist.</Message><Key>smC1842A51E22A05000000000000A386410000000100003J7M3CMY9CMULJKG6Q</Key><RequestId>B09B6836031219A8</RequestId><HostId>GIxwOGJB8DMKoIxYcqNkRDL/a1rcrPyg7hmMx+UNNtvUVgaOILdjCMe/ntfo/+bIxWG1D5ws7SU=</HostId></Error>
>
> In my callback I did not know that this is an error message. I just save it in my local file. Toss my buffer away. Now I get an error return from libcurl with some http error.
>
>
> So, the question is how do I know my callback has been called with the Server’s extended error message, so that I can save it and not write it to file and toss the buffer away ..
So you want to know how from the write callback you can determine if the
server's reply status code was an error rather than wait until
easy_perform returns? Get CURLINFO_RESPONSE_CODE [1] and compare for the
expected code. If the code is what you expect then store it and write to
file. Like
struct data {
CURL *curl;
long server_status;
FILE *fp;
};
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
struct data *data = (struct data *)userdata;
if(!data->server_status)
curl_easy_getinfo(data->curl, CURLINFO_RESPONSE_CODE,
&data->server_status);
if(data->server_status == 200) //assuming http; regardless other codes
may be returned
// write to file
else
// don't
}
struct data data;
memset(&data, 0, sizeof data);
data.curl = curl;
data.fp = your fp;
etc
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
[1]: https://curl.haxx.se/libcurl/c/CURLINFO_RESPONSE_CODE.html
-------------------------------------------------------------------
List admin: https://cool.haxx.se/list/listinfo/curl-library
Etiquette: https://curl.haxx.se/mail/etiquette.html
Received on 2016-05-18