Skip to Content

This blog is part of a collection of blog entries that shows architectural concepts and configuration of the SAP PI REST Adapter. We also added some sample scenarios to make it easier for you to understand how your scenario can be implemented using the PI REST Adapter.

If you haven’t done so far, best is to start with the very first blog PI Rest Adapter – Don’t be afraid within the blog series covering the concepts of the REST adapter. A complete list of all blog entries can be accessed from here PI REST Adapter – Blog Overview.

With release 7.31 SP15 / 7.4 SP10 we have enhanced the REST adapter supporting custom error handling. You can maintain rules for defining how the message processing should behave in certain (error) situations. For instance, you would like to ignore particular error codes, or you would like to reply with a custom message based on message content, etc. In this blog, I would like to show you the various options that you have when defining custom error handling.

From release 7.31 SP17 / 7.4 SP12 / 7.5 SP01 onwards, the custom error handling has been further enhanced in a way that situations where no errors occur can be handled. The following features have been introduced:

  • A new rule type Always
  • A new flag to inverse the rule expression
  • A new rule type checking if a message is empty
  • New variables keeping http attributes which can be used in custom message

Scenario 1 – Custom error handling on receiver side

I would like to introduce the various custom error handling options that are supported based on the REST receiver adapter. I have configured an Integration Flow from SOAP to REST which calls the REST endpoint exposed by the scenario from one of the previous blogs PI REST Adapter – Exposing a function module as RESTful service. Using the custom error handling on the REST sender side of this scenario, I am able to mock various error situations. This way, I am able to show you the behavior of the particular error situations by comparing when calling the RESTful service using either the Advanced REST Client Application in Google Chrome browser or via the additional SOAP to REST Integration Flow.

01 iflow.png

For each of the options, let’s take a closer look at how the receiver channel of adapter type REST has been maintained.

Custom error handling options

Double-click on the receiver channel of type REST, and switch to the Error Handling tab below the Adapter-Specific tab. Here, you can define rules that are validated during runtime. For each rule you have to define a condition and an action. The condition usually consists of a source and a value, the action can be either raising an error, ignoring the error, or replying with a custom message.

Fetch various http error situations and reply with respective custom message

We would like to return a custom text depending on particular error situations of the http transport layer. I have defined two rules as follows:

  • Reply with custom text <error>not found</error> if HTTP Status Text of the service call response contains the phrase Not Found
  • Reply with custom text <error>server not reachable</error> if HTTP Status Code equals either 500 or 503

In any case, the HTTP request becomes successful, i.e., the http status code is set to 200.

02 Source is error - channel.png

Let’s run the scenario that leads to an http status code 500. When directly calling the REST service using the Advanced REST Client, we get an http status code 500 – Internal Server Error.

05 customer 21.png

When calling the REST service via the SOAP to REST Integration Flow using soapUI, the http status code 500 is fetched by the rule and the respective custom message is returned.

12 soapui customer 21.png

In the message monitor, you can see that the message has been successfully processed. An audit log entry has been added showing the rule which has been applied and the action taken.

20 message moni customer 21.png

Reply with custom message in case of a runtime exception

We would like to return a custom text whenever an exception within the REST adapter occurs. In our example, the RESTful service returns an invalid JSON format so that the conversion from JSON to XML fails. I have defined the rule as follows: Reply with custom text <error>a validation error occured</error> for source Exception.

33 validation error configuration.png

If we call the RESTful service without having defined the rule, the message goes into a system error status. From the audit log in the message monitoring, you can see that an error validating the JSON input occured.

30 validation error.png

If we call the RESTful service with having the rule above active, the message will be delivered succesfully with the custom message as response. From the audit log you can see that the respective rule has been applied.

32 validation error fetched in message moni.png

Reply with custom message for a particular JSON element

If the resource, here the customer, does not exist in the backend system, the field name in the response of the service call is set to NONE. We would like to return a custom text if the value of the JSON element name equals NONE. So, as source we choose JSON Expression from the drop down menu. The rule is met if the JSON Element customer.name matches the expression NONE. As action we choose Custom Result. Within the message content we use a variable in curly brackets which is replaced by the id of the customer during runtime.

03 Source is JSON.png

When calling the REST service using the Advanced REST Client, the response in JSON format contains an element name equals NONE.

11 customer 76.png

When calling the REST service via the soapUI, the respective custom message has been returned with the id derived from the request url, here 76.

21 soapui customer 76.png

Raise an error for a particular header element value

The response should be in JSON format. If an XML is returned, an error should be raised. So, we create a rule with source HTTP Header Element checking if the http header element content-type contains the term application/xml. If the rule matches, the action should be to raise an error.

03 Source is Header Element.png

When calling the REST service using the Advanced REST Client, you can see that the response is in XML format instead of JSON, and the header element content-type is application/xml instead of application/json.

26 chrome content type xml.png

When calling the REST service via the soapUI, from the audit log in the message monitor you can see that the respective rule matches, and the message is put into an error status.
26 message moni content type xml.png

Ignore error for a particular text in payload of response

In case of any timeout when calling the REST service, we would like to ignore the error. Here, we parse the payload of the response searching for the term Timeout. So, as source we choose Text Content from the drop down menu, and maintain *Timeout* as expression. As action, we select Ignore Error from the drop down menu.

28 config timeout.png

When calling the REST service using the Advanced REST Client, we get an http status code 504 – Gateway Timeout. In the response payload, the reason is stated as Timeout.

29 chrome timeout.png

When calling the REST service via the soapUI, from the audit log in the message monitor you can see that the respective rule applied, and the message is put into status Delivered.

27 message moni timeout.png

Note: The following three scenarios are supported from release 7.31 SP17 / 7.4 SP12 / 7.5 SP01 onwards only.


Reply with custom message if response is empty

If you choose Text Content as Source, you have the option to define an action if the http result is empty. Here, select the flag Result message is empty.

01 Config.png

Reply with custom message in case of any error

We would like to reply with a custom message whenever the http status code is not 200. The custom message should provide information about the issue of the RESTful call. Define a rule with Source HTTP Status Code, select the flag Selection does NOT match, and maintain Status Code 200. As Action choose Custom Result. In the Message Content you can use the variables http_status and http_status_text in curly brackets.

01a Config.png

In case of an http status code 500, the rule applies and the respective http status code and text is displayed.

2-18-2016 4-53-26 PM.png

Always ignore errors

In case that any errors should be ignored, you can define a rule with Source Always, and Action Ignore Error.

01 Config.png

Scenario 2 – Custom error handling on sender side

Always send an http status code 202

The following scenario is supported from release 7.31 SP17 / 7.4 SP12 / 7.5 SP01 onwards.

Instead of sending an http status code 200, you would like to send the status code 202. So, create a rule on the REST sender adapter with Source Always, Action Custom Result, and HTTP Status Code equals 202. By selecting the Use Message Payload flag you ensure that your response message is kept.

01 Config.png

When calling the RESTful service from the Advanced REST Client Application in Chrome browser, you can see that the http status code has been set to 202.

02a Chrome.png

I hope this blog was helpful to understand how the custom error handling can be used. If you like to learn more, check out the other blogs in the series, accessible from the main blog PI REST Adapter – Blog Overview.

To report this post you need to login first.

54 Comments

You must be Logged on to comment or reply to a post.

  1. EDGAR ADRIAN MARTINEZ ARCE

    Hello Alexander,

    First of all, thank you for the article, I believe it explains neatly and in good detail the options we have to configure the custom error handling for the REST adapter.

    I have a question regarding the Ignore error rule, particular to an scenario we are working with.

    We are trying to handle an HTTP 500 error, that comes along with  the following response body

    {

        “errorCode”: 120322,

        “errorMessage”: “(120322) Error description”

    }

    We are trying to handle this response body, so we opted to use the ignore error configuration. Therefore the error is being ignored, but we are getting an empty payload for the response:

    /wp-content/uploads/2015/05/empty_payload_699683.png

    I would appreciate if you could point me with some hints on the feasibility of this scenario,

    Thank you in Advance,

    Edgar.

    (0) 
    1. Alexander Bundschuh Post author

      Hi Edgar,

      in the ignore error case, the payload is empty since we never know what is returned by the provider in an error case. Would you expect to keep the payload? What about having a flag where you can either remove or keep the payload of the response?

      Alex

      (0) 
      1. EDGAR ADRIAN MARTINEZ ARCE

        Hello Alexander,

        Thank you for your response, in this case we would be intending to keep the payload, since we can find a more detailed error there. A flag like that would be great, I wonder if there is an approach we could follow to implement it or if this is an option that could be added to the adapter, and if that is the case, please let us know if there is anything we could do to collaborate.

        Thank you again,

        Best Regards!

        Edgar.

        (0) 
  2. Pradeep Mysore

    Hi Alex,

    As others have expressed, Can you please tell us, How to preserve the REST response when HTTP response code is non 200.

    Currently REST receiver adapter seems to ignore the response for non 200 HTTP response code.

    -Pradeep

    (0) 
  3. EDGAR ADRIAN MARTINEZ ARCE

    Hello again Alexander,

    Thank you very much for including the error handling functionality, we are looking forward to November 🙂

    I also have another inquiry, not sure if this would be the right place, but we are trying to manage a JSON array for the response ( response beginning with “[” instead of “{” ).


    We saw a possible answer on this scn post:


    JSON to XML conversion in receiver REST communication channel


    However, we are wondering if there is any plan to support this scenario as a standard adapter scenario.


    Anyway, thank you very much again,


    I hope you have a great day,


    Best Regards !


    Edgar.

    (0) 
      1. Christian Breitsprecher

        Hi Alex,

        That’s good news, thank you for the bugfix!

        We stumbled upon another issue which happens when we have a REST receiver that expects an array in the JSON:

        In the XML schema we model those elements as 1:n. The conversion to JSON arrays works fine as long as we have at least two occurences of the element. If we only have one occurence, the XML to JSON conversion will produce {element”:”X”} instead of {element”:[“X”]}.

        As the receivers expect an array in JSON, no matter if the occurence is 1 or n, this is causing serious trouble for us. Currently we are integrating two independent partners via REST and with both we are facing the same issue.

        Is there a fix for this already (I haven’t found a note yet)?

        (0) 
  4. Pradeep Mysore

    Hi,

    We also need REST adapter to handle JSON array appropriately. Hope SAP fixes these basic issues in the next releases. REST and JSON are becoming defacto standards in exposing backend functionality as webservice. This will be a big selling point for SAP.

    -Pradeep

    (0) 
  5. Samiullah Qureshi

    Hi Alexander,

    This is really nice and informative blog. Thanks for sharing this.

    I have a question regarding the error handling. We are configuring integration with REST web-services using REST adapter with SAP PI 7.31 (SP15).  Whenever are getting errors pertaining to data we are getting HTTP 500 error in SAP PI and no other information about error. However, if I call the Web-Service using Postman with same payload, it gives the error code as 500. Also, it provides the error text saying that which field was having issue.

    Rest WS Error.jpg

    Can we catch this error message anyhow in SAP PI and send it back to source system?

    Regards,

    Samiullah.

    (0) 
      1. srinivas sistu

        Hi Alexander,

        Thank you for the blog. I have followed most of your blogs on REST adapter, they all are such nicely explained that I was able to test all of them successfully.

        I have a small doubt, how should we map the response body of the REST receiver service to sender?

        I am trying a scenario with SYNC SOAP sender and REST receiver. Everything is working except that I am not able to map the REST response back to my SOAP sender.

        Regards,

        Srinivas

        (0) 
  6. Pradeep Mysore

    Hi Alex,

    Is this feature (Processing actual HTTP response body when response code is not 200) implemented in 7.31 SP17 . We have installed  7.31 SP17 and does seem to see any option on the receiver REST adapter to handle HTTP response when HTTP response code in not 200.

    Please clarify.

    Thanks

    -Pradeep

    (0) 
      1. Pradeep Mysore

        Hi Alex,

        Thanks for the information. Are there are any SCN document explaining how to use?.

        Or any other details?. Thanks again for the quick response.

        -Pradeep

        (0) 
      1. Pradeep Mysore

        Hi Alex,

        Thanks a lot for for the quick response. Can you please tell us where we can find the metadata file (TPZ file) . Our Basis team said they applied CTC template and I still did not see new features in the screen. Sorry to bug you.

        -Pradeep

        (0) 
          1. Pradeep Mysore

            Thanks Alex. I have provide this information to BASIS. Hopefully they will be able to apply.

            Just FYI..

            Also after SP 17 patch. REST sender adapter is NOT behaving properly when Dynamic Attributes REST ID (id) is set .

            We have a sender REST adapter with below endpoint

            http://xxx.com:50000/RESTAdapter/sap/businesspartner/{partnerID}

            and when we test above endpoint from Google REST client.PI is not parsing correct value for partnerID

            http://sapp-dev-dc-v.ops.aol.com:50000/RESTAdapter/sap/businesspartner/7000057379

            DynamicConfigurationKey key = DynamicConfigurationKey.create(“http://sap.com/xi/XI/System/REST&rdquo;, “id”);

            String value = dynConf.get(key);

            Value being returned here is 7000053463 instead of 7000057379.

            7000053463 is a value from a previous request. And subsequent call to this endpoint always returns 7000053463 what it may be in the partnerID. It will reset only once only when we restart REST Sender Channel.

            I have opened a high severity incident with SAP support. Hopefully it  will resolved soon.

            Thanks

            Pradeep

            (0) 
              1. Dimitar Hristozov

                Hello,

                The upper issue where the values from previous reqests to REST sender channel are cached is solved with SAP Note 2258139 “REST sender channel is caching values from HTTP requests”

                Best regards,

                Dimitar

                (0) 
  7. Christian Breitsprecher

    Hi,

    We are on 7.4 SP13 and have a synchronous SOAP/XI to REST scenario. Is it possible to generate a fault message out of an errornous response? The fault message should include the {http_result}.

    We’ve tried to assign the sender and receiver interface fault messages and mapped them within the operation mapping. In the REST receiver channel we have added a custom result for all non HTTP 200 responses which creates a fault structure with the {http_result} within. Unfortunately this does not trigger the fault mapping, but is failing on the message mapping of the standard response.

    Also trying to do an interface split out of the standard response mapping did not trigger an exception / fault message. Instead we have a response that looks like a fault message but is not triggering the exception / fault behaviour for the sender (BPM).

    Is there any other way to create a fault message containing body information in case of a non HTTP200 response? Ideally we would be able to trigger an error instead of custom result and have the possibility to include the {http_result} in the error message.

    (0) 
    1. Alexander Bundschuh Post author

      Hi Christian,

      I would say it’s possible with the latest enhancements that we have shipped with 7.31 SP17 / 7.4 SP13 / 7.5 SP01, see also the example in my blog

      Alex

      (0) 
      1. Sachin Dhingra

        Hi Alexander,

        Thank you for wonderful series of blogs on REST.

        We are on PO 7.5 SP06 and trying to get the non-200 response back to sender sysetem. Success message is coming to mapping and to source system. But for 400 Bad request, we are not getting ADAPTER exception with an error “premature end of file” in the log.

        However, we are able to workaround as mentioned in comment to map {http_result} to source field. But, we are looking a standard way to get the error code and text as it is from REST POST operation and send it back to Sender application. Please suggest.

        Regards,
        SD

        (0) 
    2. Dimitar Hristozov

      Hello Christian,

      The fault mapping is not triggered because the REST adapter sets the message class for the generated XI response messages for non-200 HTTP calls either to Application or ApplicationResponse and not to ApplicationError.

      The issue is fixed with SAP Note 2273265.

      Best regards,

      Dimitar

      (0) 
      1. Christian Breitsprecher

        Hi Dimitar,

        We have tried out the note but it doesn’t seem to make a difference.

        I am not sure if we are using the correct procedure:

        We have assigned a fault message to both service interfaces and created the message mapping + assigned it for fault in the operation mapping.

        In the REST receiver channel we are using the setting “Selection does NOT match HTTP code 200 -> Action = custom result -> Message Content = <ns0:FaultMessage ….” within the fault message we are using {http_result}.

        When we now receive back an HTTP 401 for example, the message mapping for the fault message is not triggered. Instead the message mapping for the normal response message is being triggered and fails as the input is is not the expected response, but the FAULT structure that we are generating in the REST receiver channel.

        Is this the correct procedure?

        When we use Action = Error instead, we receive an Exception (System FAULT) but are not able to see/include any information of the {http_result}.

        (0) 
        1. Christian Breitsprecher

          If anyone is facing the same issue:

          Our current workaround is to add an optional field “error” to the response message structure of the sender which is filled with the {http_result} in the REST receiver adapter.

          The setting in the REST adapter error tab is: source = exception, action = custom result.

          The fault message from the receiver interface has been removed. Inside the message mapping of the response we check the content of the new error field. If it is filled, we throw a runtime exception in a UDF and pass the {http_result}.

          (0) 
        2. Dimitar Hristozov

          Hello Christian,

          As mentioned in SAP Note 2273265 – in your case the module parameter “setAppErrorOnCustomMessage” has to be set on true in order the message class of the response message to ApplicationError. This should be able to trigger the Fault mapping.

          Your workaround is suitable but nevertheless REST adapter message class behavior about messages generated with custom error handling is not deterministinc as it  is not clear if in this case the call is treated as successful or not. With his additional module parameter it is possible to tune this behavior to the desired one.

          Best regards,

          Dimitar

          (0) 
  8. Pradeep Mysore

    Hi Alex and Dimitar,

    We are on Netweaver 7.4 SP 12, However We are still not able to download 7.4 SP 13 with new REST Adapter feature (REST adpter non 200 response processing) . Can you please tell me when this would be available to downlaod?

    Thanks

    -Pradeep

    (0) 
  9. Muni M

    Hi Alex,

    what will happen if target is not returning any of the values.

    I am getting error like “http_result is not configured, or has an empty value “

    may adapter module can pass empty if this is not coming from target…

    (0) 
    1. Dimitar Hristozov

      Hello Muni,

      The issue with unavailability of the http_result internal variable is solved by SAP Note

      2273265 “Problem acessing error response message with internal variable and wrong message type for the generated XI message”

      Best reagrds,

      Dimitar

      (0) 
      1. Muni M

        Hi Dimitar,

        my PI system is already in 7.4 sp13.

        i am able to use http_result variable, and it gets filled when text is returned by target. this text comes for some status codes but not for all i guess.


        I dont remember the status code for which http_result is not getting filled. if it is empty, you can return empty string in the adapter module. so that one generic error handling(200 does not match) will suffice all status code error handling.

        (0) 
  10. Pradeep Mysore

    Hi Alex/Dimitar,

    I have configured a REST sender adapter with Dynamic attributes (REST ID (id)) with pattern Element as {userID}.

    In the same REST sender adapter, I have configured Custom Error handling option and trying to refer {userID} in the message content as

    <data>User ID {userID} not found</data>

    However in the actual response, value of {userID} is not getting substituted. Can you please suggest what could be wrong here?

    <data>User ID {userID} not found</data>


    Thanks

    -Pradeep

    (0) 
  11. Edgar Hußmann

    Hi Alexander
    Nice Blog!
    In the last days Ihad my first experiences in using “custom error handling” and for me this blog was an great infomation pool.
    In general I was succesfull in handling custom errors in a receiver channel – but now I ‘ve got a question:

    Where can I find an overview of usable predefined variables (like http_status or http_status_text). I would like to use values of a response header field in custom result message content – is there a variable to achieve this?

    Thanks
    Edgar

    (0) 
    1. Alexander Bundschuh Post author

      Hi Edgar,

      see Custom Error Handling – Advanced Adapter Engine – SAP Library

      According to the documentation, only the 3 variables  http_status, http_status_text, and http_result are supported. Although you can use dynamic attributes in the custom error text, on the receiver channel the dynamic attributes refer to the original request message. so this wouldn’t help you here.

      In Configuring the Receiver REST Adapter – Advanced Adapter Engine – SAP Library it is mentioned that the HTTP headers of the HTTP result message are copied into the XI message as dynamic message attributes and are therefore available for later reference. So the only option I see is that you create your custom error message within a mapping of your response, here you can then use the dynamic attributes

      Alex

      (0) 
      1. Edgar Hußmann

        Hi Alex
        thanks for quick response.
        I tried before to use headers of response message as dynamic attributes. But it’s never so easy as it looks like 🙂
        I need the value of the header parameter “location”, which is used for redirecting (with HTTP302 response code).
        I set module parameter ProceedRedirect to false – so the message isn’t redirected.  Now I can see header parameters as dynamic attríbutes in dynamic configuration view. All except one – the “location” header is missing 🙁
        So I tried custom error handling to keep this parameter – but how to get it?
        It’ s a really challenging issue …

        But nevertheless thanks for your support and this blog!

        Edgar

        (0) 
  12. Faruk Basaran

    Hi Alex,

    I am trying to use {message_result} variable for Sender Rest Channel custom error handling( In case of any error on receiver side). There is not much info how to use it, I thought it would be same as {http_result} but it is not working.

    SAP_XIAF version is : 7.40.13.20160510074834.0000

    URL: http://help.sap.com/saphelp_nw74/helpdata/en/b4/a425ee3d214e2b829e835e0046830a/content.htm

    Also: Sap Note 2175250 – New Feature: Enhancements in custom error handling

    Is there any way to get this working?

    Thanks,

    Faruk.

    (0) 
  13. Khaja Sk

    Hi Alex,

    For me also same problem,  {message_result} not working in sender channel, this is sender async channel. And the variables   http_status and http_status_text in curly brackets not working. I too updated the Sap Note 2175250, but still not working.
    What  will be problem?

    Regards,
    Khaja.

    (0) 
  14. Khaja Sk

    hello,

    my receiver REST channel is not waiting for 200 response from legacy end point. How to wait  or get confirmation 200 ok from endpoint.
    with out this 200 message my message gets Delivered status.

    Regards,
    Khaja.

    (0) 
  15. George Grix

    Hi Alex,

    Thank you so much for the detailed write-up…  I am also looking into how to capture the entire return message from a REST call and have it be recorded so it can be sent via email when an <error> tag is present.  I have tried using:

    Source:  Text Content

    Expression (Glob):  *<error>*

    Action:  Custom Result

    Message Content:  {text_content}

     

    Is {text_content} a valid variable that can be used to capture the entire results returned from the REST call?

     

    Thank you,

    George

    (0) 
  16. Kishore Enumula

    Dear Experts,

    We have Synchronous scenario that is consuming the REST Service(POST). During the POST the following exception is raised. The REST service when tested stand alone works for same data . Is there any spefific setting we are missing ?

    We are following the help.sap.com for consuming the sync service in SDN .

    com.sap.engine.interfaces.messaging.api.exception.MessagingException: com.sap.aii.adapter.rest.ejb.common.exception.CustomErrorException: Custom event handling: Error. Rule: 1 Exception

    (0) 

Leave a Reply