web
You’re offline. This is a read only version of the page.
close
Skip to main content
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)
  • Suggested answer
    Leo Muller Profile Picture
    5 on at
    RE: How to get response message Error using WebResponse?

    The exception also has the Response property, you can use that.

    try

    {

    System.Net.WebResponse webResponse = wr.GetResponse();

    System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream());

    Result = sr.ReadToEnd();

    }

    catch(System.Net.WebException ex)

    {

    System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream());

    Result = ex.Status.ToString();

    Result += sr.ReadToEnd();

    }

  • Martin Dráb Profile Picture
    236,229 Most Valuable Professional on at
    RE: How to get response message Error using WebResponse?

    The theory is that your code runs inside a transaction, which would explain why your catch clauses are ignored. You can't catch exceptions inside transactions. Therefore what you should do is verifying whether your code runs inside a transaction or not. You can see it in the Autos windows in the debugger, for instance.

  • Community Member Profile Picture
    on at
    RE: How to get response message Error using WebResponse?

    What was your second theory and proposal to workaround inside a transaction like this?

  • Martin Dráb Profile Picture
    236,229 Most Valuable Professional on at
    RE: How to get response message Error using WebResponse?

    I recommend you explore the second of my theories - that you're inside a transaction. By the way, making web service calls inside transactions is bad idea for performance and reliability reasons. So if you find out that you're indeed inside a transactions, you'll have many reasons to fix your design.

    By the way, please use Insert > Insert Code (in the rich formatting view) to paste source code.

  • Community Member Profile Picture
    on at
    RE: How to get response message Error using WebResponse?

    Hi,

    I am trying to make a POST call on the endPost method. That is where I am getting the same error and thus cannot catch it. Same 400 bad request in PostMan.When I debug it shows this in $exception {"The remote server returned an error: (400) Bad Request."} System.Net.WebException

    [ExtensionOf(classStr(SalesInvoiceJournalPost))]
    
    public final class SalesInvoiceJournalPost_Extension
    
    {
    
       protected void endPost()
    
       {
    
           next endPost();
    
           try {
    
               new InteropPermission(InteropKind::ClrInterop).assert();
    
               url = "myUrl";
    
               clrObj = System.Net.WebRequest::Create(url);
    
               request = clrObj;
    
               request.set_Method("POST");
    
               utf8 = System.Text.Encoding::get_UTF8();
    
               requestStream = request.GetRequestStream();
    
               requestStream.Close();
    
               response = request.GetResponse();
    
               responseStream = response.GetResponseStream();
    
               streamRead = new System.IO.StreamReader(responseStream);
    
               responseJson = streamRead.ReadToEnd();
    
           }
    
           catch (Exception::CLRError)
    
           {
    
               ex = CLRInterop::getLastException();
    
               info(ex.ToString());
    
               if (ex != null)
    
               {
    
                   ex = ex.get_InnerException();
    
                   if ((ex != null) && (ex is System.Net.WebException))
    
                   {
    
                       webException = ex as System.Net.WebException;
    
                       info(webexception.ToString());
    
                   }
    
               }
    
           }
    
           catch (netWebException)
    
           {
    
               warning("");
    
           }
    
           catch (serviceModelComEx)
    
           {
    
               warning("");
    
           }
    
           catch (ex)
    
           {
    
               warning("");
    
           }
    
           catch (xppEx)
    
           {
    
               warning("");
    
           }
    
           catch (targetInvocationException)
    
           {
    
               warning("");
    
           }
    
           catch
    
           {
    
               warning("");
    
           }
           streamRead.Close();
            responseStream.Close();
            response.Close();
           
           
           }

  • Martin Dráb Profile Picture
    236,229 Most Valuable Professional on at
    RE: How to get response message Error using WebResponse?

    All exceptions inherits from System.Exception, therefore trying other types won't make a difference.

    If you don't catch anything, it means either that there is no exception, you're catching it at a place where it can't be done (inside a database transaction) or that the exception is caught but you didn't notice. It's impossible to say which case it is unless you tell us what you're doing.

  • Community Member Profile Picture
    on at
    RE: How to get response message Error using WebResponse?

    Hi, did you get to find a solution to catching this exception? I'm running into the same problem.

    I've tried catching System.Exception ex, webException; System.Net.WebException netWebException; Microsoft.Dynamics.Ax.Xpp.ErrorException xppEx; and Exception::CLRError and even a catch with out an exception. None of them works.

  • Kreatif Profile Picture
    10 on at
    RE: How to get response message Error using WebResponse?

    Thanks Martin,

    Sorry for late respond.

  • Martin Dráb Profile Picture
    236,229 Most Valuable Professional on at
    RE: How to get response message Error using WebResponse?

    To be able debug, you must have a debugger attached to the running application. Therefore "Start debugging" must mean that a debugger will be attached. The difference between "Start Debugging" and "Attach to Process" is that the first one starts an application and attach the debugger to it and the latter attaches to an already running process.

  • Kreatif Profile Picture
    10 on at
    RE: How to get response message Error using WebResponse?

    Hi martin,

    i use Start Debugging, not use Attach to Process...

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…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

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

#1
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 2,258

#2
André Arnaud de Calavon Profile Picture

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

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 631 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans