# Handling API exceptions in Rasa action server

**URL:** <https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961>\
**Category:** Rasa Open Source\
**Created:** [November 6, 2019, 9:16am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961 "2019-11-06T09:16:34Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![sarankarthik](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@sarankarthik](https://forum.rasa.com/u/sarankarthik)\
**Post date:** [November 6, 2019, 9:16am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/1 "2019-11-06T09:16:34Z")

</div>

I have to handle API call exceptions in Rasa action server. For Example, I have a list of restaurant databases, which I will host it in a local server. In rasa action server, I would host this local server and access information from the database.

If wrong database has hosted, it throws 501 http error. When this error occurs, I can now log this error,but I would like to send a message as a response to user.

> If 501 error occurs,

```
For,
User Input: Can you look for cheap restaurant in centre of town
system output: I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later

```

How can I handle this in Rasa action server? Could I get any information regarding this?

---

<div class="post-metadata">

**Author:** ![tonysinghmss](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/tonysinghmss/32/5846_2.png) [@tonysinghmss](https://forum.rasa.com/u/tonysinghmss)\
**Post date:** [November 6, 2019, 9:20am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/2 "2019-11-06T09:20:35Z")

</div>

How are you making API calls from `actions.py` ? If you are using requests package, then it should be quite easy.

---

<div class="post-metadata">

**Author:** ![tonysinghmss](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/tonysinghmss/32/5846_2.png) [@tonysinghmss](https://forum.rasa.com/u/tonysinghmss)\
**Post date:** [November 6, 2019, 9:23am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/3 "2019-11-06T09:23:28Z")

</div>

Inside the run method of your Action class, you can use requests to make API call like this:

```
    try:
       log.debug(f'URL for API: {_url}')
       resp = requests.get(_url)
   except requests.exceptions.RequestException as e:
            s = getattr(e,'message', str(e))
            log.error(f'Unable to get data due to {s}.')
  message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'
  dispatcher.utter_button_message(message)
```

---

<div class="post-metadata">

**Author:** ![sarankarthik](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@sarankarthik](https://forum.rasa.com/u/sarankarthik)\
**Post date:** [November 6, 2019, 10:22am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/4 "2019-11-06T10:22:45Z")

</div>

Hi @tonysinghmssThanks for the reply. I have tried it, but still it throws me an exception instead of an error message

In run() method of my action class, I have defined as follows,

> class RestaurantInform(Action): def name(self): return “Restaurant-Inform”
> 
> ```
> def run(self, dispatcher, tracker, domain):        
> try:
> count, specific_data, name, addr, ph_no, post_code= ActionSearchRestaurants.entity_extract(self, dispatcher, tracker, domain)
>         
> if len(specific_data) != 0:
> message = dispatcher.utter_message(f"There are {count} options available. The list of Restaurant names are {specific_data}. Could you tell me which one do you prefer?")
> return message
> elif len(addr)!=0 and len(ph_no)!=0 and len(post_code)!=0:
> message_1 = dispatcher.utter_message(f"The restaurant {name} is located at {addr} and their phone number is {ph_no}. The post code of the restaurant is {post_code}")  
> return message_1
> else:
> pass
> except requests.exceptions.RequestException as e:
> s = getattr(e,'message', str(e))
> logger.info(f'Unable to get data due to {s}.')
> message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'
> dispatcher.utter_message(message)
> 
> ```

Instead of giving me the message

```
 message = 'I am sorry for the inconvenience, I have encountered an Internal service error. Could you please try again later'

```

I get the following exception,

> Your input → can you look for cheap restaurants in centre of town?  
> Could you give me some other suggestion?

> 2019-11-06 11:09:56 ERROR rasa.core.processor - Encountered an exception while running action ‘Action-Search’. Bot will continue, but the actions events are lost. Please check the logs of your action server for more information.

> 2019-11-06 11:09:57 ERROR rasa.core.processor - Encountered an exception while running action ‘Restaurant-Inform’. Bot will continue, but the actions events are lost. Please check the logs of your action server for more information.

---

<div class="post-metadata">

**Author:** ![tonysinghmss](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/tonysinghmss/32/5846_2.png) [@tonysinghmss](https://forum.rasa.com/u/tonysinghmss)\
**Post date:** [November 6, 2019, 10:31am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/5 "2019-11-06T10:31:45Z")

</div>

Can you put log of your` actions.py`? That will help in better understanding of your issue.

---

<div class="post-metadata">

**Author:** ![sarankarthik](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@sarankarthik](https://forum.rasa.com/u/sarankarthik)\
**Post date:** [November 6, 2019, 10:55am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/6 "2019-11-06T10:55:22Z")

</div>

This is the information, which I have received,

> 2019-11-06 11:52:16 INFO rasa\_sdk.endpoint - Action endpoint is up and running. on (‘0.0.0.0’, 5055)

> 2019-11-06 11:52:35 WARNING rasa\_sdk.endpoint - Your versions of rasa and rasa\_sdk might not be compatible. You are currently running rasa version 1.4.0a1 and rasa\_sdk version 1.3.2.

> To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa and rasa\_sdk.

> 2019-11-06 11:52:35 DEBUG rasa\_sdk.executor - Received request to run ‘Restaurant-Request’

> 2019-11-06 11:52:35 DEBUG rasa\_sdk.executor - Finished running ‘Restaurant-Request’

> 127.0.0.1 - - [2019-11-06 11:52:35] “POST /webhook HTTP/1.1” 200 220 0.000000

> 2019-11-06 11:52:36 WARNING rasa\_sdk.endpoint - Your versions of rasa and rasa\_sdk might not be compatible. You are currently running rasa version 1.4.0a1 and rasa\_sdk version 1.3.2.

> To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa and rasa\_sdk.

> 2019-11-06 11:52:36 DEBUG rasa\_sdk.executor - Received request to run ‘Action-Search’

> 2019-11-06 11:52:36 DEBUG urllib3.connectionpool - Starting new HTTP connection (1): 127.0.0.1:3128

> 2019-11-06 11:52:36 DEBUG urllib3.connectionpool - [http://127.0.0.1:3128](http://127.0.0.1:3128) “GET [http://localhost:5000/restaurant](http://localhost:5000/restaurant) HTTP/1.1” 404 447

> 2019-11-06 11:52:36 DEBUG error-info.log - The requested URL could not be found. I could not disclose whether it is temporary or permanent

> 2019-11-06 11:52:36 ERROR flask.app - Exception on /webhook [POST]

Traceback (most recent call last):

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 2292, in wsgi\_app response = self.full\_dispatch\_request()

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1815, in full\_dispatch\_request rv = self.handle\_user\_exception(e)

File “c:\apps\sa2446\lib\site-packages\flask\_cors\extension.py”, line 161, in wrapped\_function return cors\_after\_request(app.make\_response(f(\*args, \*\*kwargs)))

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1718, in handle\_user\_exception reraise(exc\_type, exc\_value, tb)

File “c:\apps\sa2446\lib\site-packages\flask\_compat.py”, line 35, in reraise raise value

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1813, in full\_dispatch\_request rv = self.dispatch\_request()

File “c:\apps\sa2446\lib\site-packages\flask\app.py”, line 1799, in dispatch\_request return self.view\_functionsrule.endpoint

File “c:\apps\sa2446\lib\site-packages\flask\_cors\decorator.py”, line 128, in wrapped\_function resp = make\_response(f(\*args, \*\*kwargs))

File “c:\apps\sa2446\lib\site-packages\rasa\_sdk\endpoint.py”, line 59, in webhook response = executor.run(action\_call)

File “c:\apps\sa2446\lib\site-packages\rasa\_sdk\executor.py”, line 259, in run validated\_events = self.validate\_events(events, action\_name)

File “c:\apps\sa2446\lib\site-packages\rasa\_sdk\executor.py”, line 209, in validate\_events for e in events:

TypeError: ‘HTTPError’ object is not iterable 127.0.0.1 - - [2019-11-06 12:36:30] “POST /webhook HTTP/1.1” 500 411 0.015621

---

<div class="post-metadata">

**Author:** ![Shaan27](https://avatars.discourse-cdn.com/v4/letter/s/a6a055/32.png) [@Shaan27](https://forum.rasa.com/u/Shaan27)\
**Post date:** [March 10, 2021, 8:46am UTC](https://forum.rasa.com/t/handling-api-exceptions-in-rasa-action-server/20961/7 "2021-03-10T08:46:24Z")

</div>

Hi,

Could you please suggest, how to track information, errors in a logger? I a using the below codes in my action file but it’s not capturing anything, neither any log files created as of now. (its also not showing any error.

```
import logging
logging.basicConfig(filename='logfile.log', format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger( __name__ )

def submit(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict]:
	
	 try:
	........
	........
	........

except Exception as e:
            msg = 'Unfortunately I am not able to extract requested information! <br>You can still contact us via email 🙂'
            dispatcher.utter_message(text= msg)
            logger.error(e)
            # logger.exception()
            logger.exception("Failed to extract data for " + project + "(" + query + ")")
            return []

```

Will appreciate your response.
