Improved error handling and set Content-Length header