improve error checking and route to avoid memory leaks