Added proper error message handling to return a 500 code and meaningful message to the user.