Improve error handling
Use send_error instead of write_error