Improve error handling and add IP validation