nginx - "Connection reset by peer while reading response header from upstream" error while using PHP(7.4) Exception

one text

I am getting 502 bad gateway whenever I throw an Exception in Phalcon 4 application. I am using default PHP Exception class that implements Throwable interface.

throw new Exception ("Some error message here", 500);

I wasted so much time and saw all posts about this issue but couldn't find solution for it.

When I check my nginx logs it always says

Connection reset by peer while reading response header from upstream

Sometimes(15%) it throws the exception and gives me the message but mostly it just shows 502.

I am pretty sure it is not related to my code because if that was the case then it shouldn't even work sometimes.

Source