How to get response from aiohttp ClientError? - aiohttp

Using aiohttp, if you set raise_for_status=True, it will raise a ClientError exception.
Is it possible to access the server's response in that ClientError exception?
For instance, a server could return a 4xx error, with a JSON response explaining why, and it would be interesting to access it to manage the error (such as Stripe's API).
try:
async with aiohttp.ClientSession() as session:
response = await session.get('http://127.0.0.1:5000/auth/user', raise_for_status=True)
except aiohttp.ClientError as e:
print(e.response.content) # ?
Is it possible to access the server's response from the exception part?

If you don't want to set raise_for_status=False (although I don't understand why you wouldn't) you can catch the exception and grab the response json like so:
try:
async with aiohttp.ClientSession() as session:
response = await session.get('http://127.0.0.1:5000/auth/user', raise_for_status=True)
except aiohttp.ClientError as e:
json = await response.json()
# do something with json
# maybe you want to raise your own exception
# if not, just re-raise e
raise e

Related

How I can edit followUp message (discord.py)?

I have this code, however I don't understand how it is possible to edit the followup message. Thanks!
#bot.command()
async def button(ctx):
view=View()
button_create = Button(label="CREATE", style=discord.ButtonStyle.green)
view.add_item(button_create)
await ctx.send(view=view)
async def button_callback(interaction):
await interaction.response.defer()
await asyncio.sleep(delay=1)
await interaction.followup.send("Hi", ephemeral=True) # How can i edit this message? -_-
button_create.callback = button_callback
I tried to use "interaction.followup.edit_message("Something")", but i got error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "Something" is not snowflake.
followup.send() returns the WebhookMessage object that it sent if you set the wait kwarg to True, so you can store it in a variable and call .edit() on it.
From the send docs:
wait (bool) – Whether the server should wait before sending a response. This essentially means that the return type of this function changes from None to a WebhookMessage if set to True.

Can't respond to Interaction after using interaction.response.defer() [Nextcord]

I have a slash command, but it requires few seconds for processing. Since Discord limitation for responding to interactions seems to be 3s, i found on the documentation the interaction.response.defer() method, that should tell Discord that i've recieved the command (not to throw the error "Interaction didn't responded.")
#client.slash_command(description="Test command", guild_ids=[123456789123456789])
async def test(interaction: nextcord.Interaction):
await interaction.response.defer()
await asyncio.sleep(10) # Doing stuff
await interaction.response.send_message("My actual content")
But I get this error :
nextcord.errors.InteractionResponded: This interaction has already been responded to before
What am I doing wrong ?
interaction.followup.send() should be used instead of send_message()

Catching exception but browser still shows error page

I have a handler that is more or less this:
async def handler(request):
response = web.StreamResponse(headers={
'Content-Type': 'text/plain; charset=utf-8',
'Connection': 'keep-alive',
})
response.enable_chunked_encoding()
await stream_response.prepare(request)
try:
await do_a_thing(response) # writes into response
except Exception as e:
# log the exception. I sometimes catch a CancelledError here
await response.write_eof()
return response
When nothing goes wrong, the page is generated fine.
When a CancelledError occurs in do_a_thing(), the browser shows an error page ERR_INCOMPLETE_CHUNKED_ENCODING, even though:
the CancelledError is definitely NOT happening on writing the response (it's during an HTTP GET to another URL in do_a_thing())
I catch the exception
I don't do anything different to write the EOF and return the response
I must be doing something wrong, or not doing something right, but I can't tell what.
Can anyone see what it might be?

Respond to user and continue to run async functions

I want to respond to user as soon as I received the request, then continue to save data to database
async def index(request):
data = await request.post()
response.write("done")
async with request.app.mysqlpool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("INSERT INTO ...")
If I try to wrap the part after request.write to separate function and than call it with run_in_executor - it doesn't allow awaitable functions inside (TypeError: coroutines cannot be used with run_in_executor())
Is there a way to do it in aiohttp?
Push await response.drain() just after response.write(...) call.
It doesn't exactly guarantee that data are sent through the wire but it's the closest solution.

how can I get more error messages out of solrj SolrException

When I send queries to Solr using solrj, I sometimes get SolrException's thrown. When I dig through the exception, it just says "Bad Request", and gives the HTTP return code (which is 400).
When I take the request URL and put it in my browser, I was able to see a richer error message. The browser displays an error message saying one of the fields names is not valid.
I would like to be able to capture this inside my log file. I was able to capture this by copying all the parameters to an Apache HTTP Client POST request (I'm using POST and not GET because GET made the URL too long) and re-executing the request, but this is inefficient. Is there a way to get error message out of SolrException directly?
Here's what I'm doing:
catch (SolrServerException e) {
if(e.getRootCause() instanceof SolrException) {
SolrException ee = (SolrException) e.getRootCause();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(SOLR_URL);
// copy params over
Iterator<String> iter = request.getParams().getParameterNamesIterator();
while(iter.hasNext()) {
String p = iter.next();
method.setParameter(p, request.getParams().get(p));
}
int statusCode;
try {
// re execute and display the error message
statusCode = client.executeMethod(method);
logger.error(method.getResponseBodyAsString());
} catch (Exception e1) {
// TODO Auto-generated catch block
}
}
These messages aren't available via SolrJ. You can see them in solr's log file, but there is no way to capture them in your client, since solr only returns the 400 error status with a generic message to the client :(

Resources