Improved database query error handling