web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

How to get response message Error using WebResponse?

(0) ShareShare
ReportReport
Posted on by 10

str         url, valueStr, json, jsonString, message;
Array       jsonArray;
Map         dataMap;
MapIterator mi;
Container   conData;

System.Net.HttpWebRequest       request;
System.Net.HttpWebResponse      response;
System.Byte[]                   byteArray;
System.IO.Stream                dataStream;
System.IO.StreamReader          streamRead;
System.Text.Encoding            utf8;
System.Exception                ex;

CLRObject                       clrObj;
Newtonsoft.Json.Linq.JObject    object;

System.Net.WebHeaderCollection  headers = new System.Net.WebHeaderCollection();

object = new Newtonsoft.Json.Linq.JObject();
object.Add("PortId", _port);
object.Add("PortName", _portName);

json    = Newtonsoft.Json.JsonConvert::SerializeObject(object);

url     = strFmt("%1", #longURL);
clrObj  = System.Net.WebRequest::Create(url);

request = clrObj;
request.Headers = headers;

utf8        = System.Text.Encoding::get_UTF8();
byteArray   = utf8.GetBytes(json);
request.set_Method("POST");
request.set_KeepAlive(true);
request.ContentType = "application/json";
request.set_ContentLength(byteArray.Length);

dataStream  = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.get_Length());

try
{
	response    = request.GetResponse();

	if(response.StatusCode == System.Net.HttpStatusCode::OK)
	{
		dataStream  = response.GetResponseStream();
		streamRead  = new System.IO.StreamReader(dataStream);
		jsonString  = streamRead.ReadToEnd();
		message     = KREGlobal::parseJsonVMS(jsonString);
		info(strFmt("%1", message));
	}
	else
	{
		info Error(strFmt("Error 1 -> %1", message));
	}
}
catch
{
	info Error(strFmt("Error 2 -> %1", message));
}

dataStream.Close();
response.Close();

Hi all,

i want to get response from API if my request data not OK.

i try like this code for get info error, but i can't get info error if request data not OK.

can you help me? Thanks.

I have the same question (0)
  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    What kind of problem do you have with it? I see that your code isn't even trying to do that.

    I think you should catch System.Net.WebException and then access its Response property.

  • Sergei Minozhenko Profile Picture
    23,093 on at

    Hi,

    Probably you can use StatusDescription property (docs.microsoft.com/.../system.net.httpwebresponse.statusdescription

    For catch statement check CLRException (docs.microsoft.com/.../how-to-catch-exceptions-thrown-from-clr-objects)

  • Kreatif Profile Picture
    10 on at

    Thanks Martin Drab,

    i want to get error if data not valid in API.

    if i user postMan, i can get error message in body with status 400 Bad Request.

    1732.Error.jpg

    but, if i try use my code, i can't get message error based on my script.

    try
    {
    	response    = request.GetResponse();
    
    	if(response.StatusCode == System.Net.HttpStatusCode::OK)
    	{
    		dataStream  = response.GetResponseStream();
    		streamRead  = new System.IO.StreamReader(dataStream);
    		jsonString  = streamRead.ReadToEnd();
    		message     = KREGlobal::parseJsonVMS(jsonString);
    		info(strFmt("%1", message));
    	}
    	else
    	{
    		throw Error(strFmt("Error 1 -> %1", message));
    	}
    }
    catch
    {
    	throw Error(strFmt("Error 2 -> %1", message));
    }

    error automatic show message "The remote server returned an error: (400) Bad Request." info Error 1 or Error 2 not show.

  • Kreatif Profile Picture
    10 on at

    Thanks Sergei Minozhenko,

    i just want to show my error if API not valid.

    because if data valid, i can get info use condition :

    if(response.StatusCode == System.Net.HttpStatusCode::OK)

    {

    ////

    }

    but if data not valid or statusCode not OK (200), i can't get info error based on my script.

    if(response.StatusCode == System.Net.HttpStatusCode::OK)

    {

    ////

    }

    else

    {

    throw Error(strFmt("Error 1 -> %1", message));

    }

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    It seems that you didn't get my suggestion, so let me show you an example of what I meant:

    F&O has a much better way for catching CLR exceptions than what's covered in the documentation page for AX 2012. Take a look:
    
    System.Net.WebException webException;
    
    try
    {
        ...
    }
    catch (webException)
    {
        // Here you can access things like webException.Response.StatusCode
    }

    Please use the debugger to see what exactly is going on in your code. You handle both exceptions and non-OK statuses in the same way, therefore you can't know which situation occurred.

  • Kreatif Profile Picture
    10 on at

    Thanks Martin,

    actually my script like this.

    System.Net.WebHeaderCollection  headers = new System.Net.WebHeaderCollection();
    
    object = new Newtonsoft.Json.Linq.JObject();
    object.Add("PortId", _port);
    object.Add("PortName", _portName);
    
    json    = Newtonsoft.Json.JsonConvert::SerializeObject(object);
    
    url     = strFmt("%1", #longURL);
    clrObj  = System.Net.WebRequest::Create(url);
    
    request = clrObj;
    request.Headers = headers;
    
    utf8        = System.Text.Encoding::get_UTF8();
    byteArray   = utf8.GetBytes(json);
    request.set_Method("POST");
    request.set_KeepAlive(true);
    request.ContentType = "application/json";
    request.set_ContentLength(byteArray.Length);
    
    dataStream  = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.get_Length());
    
    response    = request.GetResponse();
    
    if(response.StatusCode == System.Net.HttpStatusCode::OK)
    {
    	dataStream  = response.GetResponseStream();
    	streamRead  = new System.IO.StreamReader(dataStream);
    	jsonString  = streamRead.ReadToEnd();
    	message     = KREGlobal::parseJsonVMS(jsonString);
    	info(strFmt("%1", message));
    }
    else
    {
    	info(strFmt("Error 1 -> %1", message));
    }
    
    dataStream.Close();
    response.Close();

    Just one exception.

    and if i debug if data not valid, my code stop in.

    response    = request.GetResponse();

    and go to.

    dataStream.Close();
    response.Close();

    not read my info error for status non-OK.

    i will try use System.Net.WebException.

    Thanks.

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    What you're saying doesn't make sense to me. It starts making sense if I imagine that you still have try/catch statement as in the code snippet that you showed at the beginning. Then it's a prove that GetResponse() throws an exception and your code where you're trying to get the message won't ever be called. Here you see the importance of debugging - you thought that your code does one thing but the debugger showed you that it does something else.

    Catching the exception (as I suggested) will give you an opportunity to extra error details.

  • Kreatif Profile Picture
    10 on at

    Hi martin,

    Please suggest me, whats wrong. i try to use exception System.Net.WebException.

    try
    {
    	System.Net.WebHeaderCollection  headers = new System.Net.WebHeaderCollection();
    
    	object = new Newtonsoft.Json.Linq.JObject();
    	object.Add("PortId", _port);
    	object.Add("PortName", _portName);
    
    	json    = Newtonsoft.Json.JsonConvert::SerializeObject(object);
    
    	url     = strFmt("%1", #longURL);
    	clrObj  = System.Net.WebRequest::Create(url);
    
    	request = clrObj;
    	request.Headers = headers;
    
    	utf8        = System.Text.Encoding::get_UTF8();
    	byteArray   = utf8.GetBytes(json);
    	request.set_Method("POST");
    	request.set_KeepAlive(true);
    	request.ContentType = "application/json";
    	request.set_ContentLength(byteArray.Length);
    
    	dataStream  = request.GetRequestStream();
    	dataStream.Write(byteArray, 0, byteArray.get_Length());
    
    	response    = request.GetResponse();
    	dataStream  = response.GetResponseStream();
    	
    	dataStream.Close();
    	response.Close();
    }
    catch(webException)
    {
    	info(strFmt("Data not valid"));
    }

    if i debug this code use wrong data, code stop in : catch(webException) with message "The remote server returned an error: (400) Bad Request.and not get my info.

    Why my info can't show if data not valid?

    Because, actually i have another action if data not valid. So, i wanna get this condition.

    Thanks.

  • Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    Try running your code without the debugger attached.

  • Verified answer
    Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at

    By the way, there is another problem with your code. You keep streams open if an exception is thrown. You should close them in both cases - if the try block completes without any error and if it fails. You can either utilize finally (try can be used with catch, with finally or with both catch and finally), or make it even simpler with using.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 660 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 549 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 307 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans