System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
When updating the same record from Postman, a more specific and user-friendly error message is displayed:
> Data may have been modified or deleted since entities were loaded.
internal final class APIClientCallRunnableClass
{
public static void main(Args _args)
{
APIClientCallRunnableClass::APICallHttpWebRequest();
}
public static void APICallHttpWebRequest()
{
System.Net.HttpWebRequest request;
System.IO.Stream stream;
System.Exception sysEx;
System.Net.WebException webEx;
str apiUrl, apimSubscriptionKey, xClientId, mimeType, responseBody;
apiUrl = 'https://3rd-party-application-api-url';
apimSubscriptionKey = 'my-subscription-key';
xClientId = 'my-client-id';
mimeType = 'application/json';
request = System.Net.WebRequest::Create(apiUrl) as System.Net.HttpWebRequest;
request.Method = 'PUT';
request.ContentType = 'application/json';
// Set the request headers
System.Net.WebHeaderCollection headerCollection = request.Headers;
headerCollection.Set('Ocp-Apim-Subscription-Key', apimSubscriptionKey);
headerCollection.Set('X-Client-Id', xClientId);
headerCollection.Set('name', mimeType);
var utf8 = System.Text.Encoding::get_UTF8();
// Set the request body
var byteArrayPayload = utf8.GetBytes("{\"accountCode\":\"999991\",\"accountName\":\"999991 ADDED/UPDATED AGAIN\",\"entityCode\":\"USMF\",\"entityName\":\"Contoso Entertainment System USA\",\"id\":9739}");
try
{
// send out the payload
using(System.IO.Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArrayPayload, 0, byteArrayPayload.Length);
}
// request.GetResponse() may already result in an error if the request was e.g. a Bad Request(Status Code 400). This should be handled upstream via our global error handling.
using(System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
{
stream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
responseBody = reader.ReadToEnd();
}
}
catch (webEx)
{
Error(strFmt('An error occured while updating record: %1', webEx.Message));
}
catch (sysEx)
{
Error(strFmt("An error occured while updating record: %1", sysEx.Message));
}
}
}